skip to content

In ASP.NET Core 10 Minimal APIs, what does builder.Services.AddValidation() do, and what happened to DataAnnotations on handler parameters before it?

level: juniorimportance: must knowfreq 55%

answer

  1. new in .NET 10
  2. earlier Minimal APIs ignored the attributes
  3. a built-in endpoint filter per endpoint
  4. 400 with HttpValidationProblemDetails
  5. Microsoft.Extensions.Validation namespace and package

basics

~20 s

AddValidation switches on built-in validation in .NET 10: a framework endpoint filter checks DataAnnotations and IValidatableObject on bound parameters and body types, nested members included, and answers 400 before the handler runs. Earlier Minimal APIs ignored those attributes.

solid answer

~50 s

Up to .NET 9, Minimal APIs bound parameters but never ran DataAnnotations; only MVC validated, through `ModelState` and `[ApiController]`, so Minimal API code validated by hand in the handler or in its own endpoint filter. In ASP.NET Core 10, `builder.Services.AddValidation()` registers `ValidationOptions`, and every endpoint with something to validate gets a built-in validation filter. The filter checks attributes on the parameters themselves (query, header and route values) and on the properties of complex types such as the JSON body, recursing into nested objects and collection items, and runs `IValidatableObject.Validate` on objects whose fields passed. If anything fails it answers 400 with an `HttpValidationProblemDetails` body, written through `IProblemDetailsService` when one is registered, and the handler never runs. The types live in the `Microsoft.Extensions.Validation` namespace and package, which a web project already gets from the shared framework.

code

csharp · 25 lines
csharp
using System.ComponentModel.DataAnnotations;

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

app.MapPost("/reservations", (SeatReservation reservation, [Range(1, 12)] int carriage) =>
    TypedResults.Created($"/reservations/{reservation.TrainNumber}", reservation));
app.Run();

public sealed class SeatReservation
{
    [Required, StringLength(8)]
    public string? TrainNumber { get; set; }
    public List<Passenger> Passengers { get; set; } = [];
}

public sealed class Passenger
{
    [Required(ErrorMessage = "Passenger name is required.")]
    public string? FullName { get; set; }
    [Range(0, 120, ErrorMessage = "Age must be between 0 and 120.")]
    public int Age { get; set; }
}

go deeper

for a junior

Recall that .NET 10 added AddValidation, that it checks DataAnnotations on parameters and request types before the handler runs, and that a failure is a 400 problem response.

for a middle

Explain what AddValidation registers, that the work is done by a framework endpoint filter, which arguments it checks, and how IProblemDetailsService shapes the failure.

for a senior

Plan the migration: remove hand-written validation filters and handler checks once AddValidation covers them, keep FluentValidation where rules need it, and avoid validating the same request twice.

for a principal

Decide where validation belongs across services: declarative request rules at the edge with AddValidation, business invariants in the domain, and one consistent error shape for every API.

## Before .NET 10 Minimal APIs have always bound handler parameters, but up to ASP.NET Core 9 they **never ran DataAnnotations**. A `[Required]` or `[Range]` on a request type was simply ignored, and invalid values reached the handler. Only MVC validated, through `ModelState` and the automatic 400 that `[ApiController]` adds. Minimal API code therefore did one of three things: - called `Validator.TryValidateObject` or a FluentValidation validator inside the handler; - wrote its own endpoint filter that inspected the arguments; - or accepted unvalidated input. ## What `AddValidation` switches on ASP.NET Core 10 adds built-in validation for Minimal APIs, enabled by one call: ```csharp builder.Services.AddValidation(); ``` 1. It registers `ValidationOptions`, with a runtime resolver that reads validation attributes placed directly on handler parameters, and a **source-generated resolver** that knows the validatable properties of your request types. 2. When each endpoint is built, the framework sees those options and, unless the endpoint opted out, adds a **validation filter** to it. If the handler has no parameter worth validating, the filter adds no per-request work. 3. On each request the filter validates every bound, non-service argument: attributes on the parameter, then the properties of complex types, nested objects and collection items, then type-level attributes and `IValidatableObject` (these two only for objects whose properties passed). 4. If any error was collected, it sets status **400** and returns an `HttpValidationProblemDetails` with an `errors` dictionary. When an `IProblemDetailsService` is registered (for example by `AddProblemDetails()`), the body is written through it; otherwise it is written as `application/problem+json`. The handler does not run. Without `AddValidation`, nothing changes: .NET 10 Minimal APIs ignore the attributes exactly as before. ## A rail-booking example ```csharp builder.Services.AddValidation(); app.MapPost("/reservations", (SeatReservation reservation, [Range(1, 12)] int carriage) => TypedResults.Created($"/reservations/{reservation.TrainNumber}", reservation)); ``` A `POST /reservations?carriage=14` whose body lacks `TrainNumber` gets one 400 listing both problems: `carriage` (a parameter attribute) and `TrainNumber` (a property of the body type). Rules on each passenger in `Passengers` are checked too. ## Where the pieces live | Piece | Namespace | Status in 10 | |---|---|---| | `AddValidation(Action<ValidationOptions>?)` | `Microsoft.Extensions.DependencyInjection` | stable | | `ValidationOptions` (`MaxDepth`, `Resolvers`) | `Microsoft.Extensions.Validation` | `MaxDepth` stable, `Resolvers` experimental | | `[ValidatableType]`, `[SkipValidation]` | `Microsoft.Extensions.Validation` | experimental (ASP0029) | | `DisableValidation()` | `Microsoft.AspNetCore.Builder` | stable | The validation types sit in the `Microsoft.Extensions.Validation` package so they can be used outside HTTP; a web project gets them from the ASP.NET Core shared framework without a package reference. ## What it does not do - It does not touch MVC controllers, which keep validating through `ModelState`. - It does not run FluentValidation validators; those still need their own wiring. - It does not validate parameters resolved from DI. - It does not return 422; the status is 400. ## What interviewers listen for - That this is new in .NET 10, and what Minimal APIs did before it. - That it runs as an endpoint filter before the handler, and the shape of the failure response. - That it is opt-in through `AddValidation` and covers nested objects and collections.

  • If AddProblemDetails is also registered, how does that change the validation 400?
    The validation filter asks `IProblemDetailsService` to write the `HttpValidationProblemDetails`. If a writer handles it, the filter returns an empty result so nothing is written twice, and any customisation registered for problem details, such as extra fields, applies to validation failures too. Without the service, the filter returns the problem object itself with content type `application/problem+json`.
  • Can a custom ValidationAttribute used by AddValidation get services from DI?
    Yes. The filter builds each `ValidationContext` with `HttpContext.RequestServices` as its service provider, so inside `IsValid(object? value, ValidationContext validationContext)` an attribute can call `validationContext.GetService(typeof(IStationDirectory))` to check, for example, that a station code exists.
  • Does AddValidation make [ApiController]-style ModelState available in a Minimal API handler?
    No. Minimal APIs have no `ModelState`. Validation happens in a filter before the handler, and a failed request never reaches the handler at all, so there is nothing to inspect inside it.

  • Minimal APIs have always enforced DataAnnotations, just like [ApiController] controllers.
  • AddValidation needs a check of ModelState.IsValid inside each handler.
  • AddProblemDetails alone turns on DataAnnotations validation for Minimal APIs.
  • A failed AddValidation check answers 422 Unprocessable Entity.
  • AddValidation also validates services injected into the handler.

Assumes ASP.NET Core 10: built-in Minimal API validation (AddValidation) is new in 10; ASP.NET Core 8 and 9 Minimal APIs ignore DataAnnotations.