Data Validation in .NET 10 Minimal APIs

Data Validation in .NET 10 Minimal APIs

Starting with .NET 10, native validation support is now available for Minimal APIs.

Validating data in Minimal APIs meant writing extra boilerplate code or adopting external solutions.

Now, developers who favor the minimalist approach no longer have to compromise on the strength of automatic validation.

The framework lets you define validation rules directly on route parameters, HTTP headers, and request bodies, all using the familiar Data Annotations system.

What Are Data Annotations?

Data Annotations are .NET attributes that define validation rules and metadata for your classes and properties. By decorating properties with attributes like [Required], [EmailAddress], or [StringLength], you automatically validate data without writing additional code. They provide a declarative, reusable way to enforce constraints across your application.

Example:

C#
				using System.ComponentModel.DataAnnotations;

public class CreateUserRequest
{
    [Required]
    [StringLength(100, MinimumLength = 3)]
    public string Name { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }
}
			

Data Annotations and Minimal APIs

Data Annotations became officially supported in Minimal APIs starting with .NET 8, though the framework supported them earlier without automatic validation.

Before this integration, even when you decorated models with attributes like [Required] or [EmailAddress], the Minimal API pipeline wouldn’t validate them automatically, unlike traditional controller APIs.

Minimal APIs were designed to be lightweight and performant with minimal overhead. When introduced in .NET 6, the goal was maximum simplicity.

Automatic validation adds complexity to the pipeline, model binding, attribute checking, and error handling all require extra processing that contradicted the “minimal” philosophy.

Without native validation, developers had to choose between manual validation or external libraries like FluentValidation, custom middleware, or switching to MVC controllers entirely. This defeated the purpose of using Minimal APIs for straightforward projects.

What changed in .NET 10?

.NET 10 automatically validates request data when you enable the feature. The runtime checks query strings, headers, and request bodies against your Data Annotations attributes.

Let’s start by registering it in our program.cs file:

C#
				builder.Services.AddValidation();
			

That’s it. The framework registers everything needed and automatically validates all compatible endpoints.

Now, dd validation directly to your endpoint parameters:

C#
				app.MapPost("/users", 
    ([Required] string name, [EmailAddress] string email) 
        => TypedResults.Ok("User created"));
			

If validation fails, the API automatically returns a 400 Bad Request with error details.

Here, name is required and email must be a valid email format.

You can disable automatic validation for specific endpoints using .DisableValidation():

C#
				app.MapPost("/users", 
    ([Required] string name, [EmailAddress] string email) 
        => TypedResults.Ok("User created"))
    .DisableValidation();
			

Creating Custom Validations

Create a class that inherits from ValidationAttribute and override the IsValid method:

C#
				public class EvenNumberAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null) 
        {
            return true;
        }

        if (int.TryParse(value.ToString(), out int number))
        {
            return number % 2 == 0;
        }

        return false;
    }
}
			

Apply it to your model:

C#
				public class ProductRequest
{
    [Required]
    [StringLength(100, MinimumLength = 3)]
    public string Name { get; set; }

    [EvenNumber(ErrorMessage = "Quantity per box must be an even number")]
    public int QuantityPerBox { get; set; }
}
			

Conclusion

.NET 10 brings powerful, integrated validation to Minimal APIs through Data Annotations, eliminating the need for manual checks or external libraries.

Whether using built-in validators like [Required] and [EmailAddress] or creating your own custom validators, the framework handles everything automatically with minimal code.

If you’re not yet leveraging Minimal APIs in your ASP.NET projects, this might be the perfect moment to explore them.

Start using Data Annotations in your Minimal APIs today and build robust, production-ready endpoints with ease.

Share the Post:
plugins premium WordPress