loading experience

ASP.NET Core

Minimal APIs in .NET 10: automatic data validation

With AddValidation, Minimal APIs validate parameters and request bodies and respond with standard errors.

Minimal APIs in .NET 10: automatic data validation

Minimal APIs are the most direct way to write HTTP APIs in ASP.NET Core. Up to .NET 9, validating incoming data had to be done by hand or with external libraries; in .NET 10 it is built in.

Invalid data never reaches the endpoint code.
Invalid data never reaches the endpoint code.

Enabling validation

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();

var app = builder.Build();

app.MapPost("/customers", (NewCustomer customer) =>
    TypedResults.Created($"/customers/{customer.Email}", customer));

app.Run();

public record NewCustomer(
    [Required, StringLength(100)] string Name,
    [Required, EmailAddress] string Email,
    [Range(18, 120)] int Age);

If the request body does not respect the rules, the endpoint is not even executed: the framework responds with 400 Bad Request and a ProblemDetails object listing the invalid fields.

What gets validated

  • Route, query and header parameters with validation attributes.
  • JSON bodies, including nested objects and collections.
  • Types implementing IValidatableObject for rules involving several fields.

Excluding an endpoint

app.MapPost("/raw-import", (RawData data) => Results.Accepted())
   .DisableValidation();

Good practices

Attribute validation checks the shape of the data; business rules (does the customer already exist? is the product available?) stay in the application service. Keeping the two levels separate makes both easier to test.

Comments (0)

No comments yet.

Leave a comment