Request validation in ASP.NET Core .NET 10: DataAnnotations and IValidatableObject, ModelState and the [ApiController] automatic ValidationProblemDetails 400, FluentValidation (manual or via filters), AddValidation() for Minimal APIs, and the split between input validation and domain/business rules.
I validate input at the edge and business rules in the application or domain layer. For input, DataAnnotations ([Required], [Range], [StringLength]) and IValidatableObject on request DTOs are the baseline. In controllers, binding fills ModelState and [ApiController] returns a 400 ValidationProblemDetails before the action runs. In Minimal APIs on .NET 10, builder.Services.AddValidation() uses a source generator to validate parameters and return the same 400 ProblemDetails; before .NET 10 you needed a filter. FluentValidation is my choice for complex, conditional or async rules; I call it explicitly or from a filter, because its automatic MVC integration is deprecated. Business rules like stock levels or uniqueness are checked where the data lives and returned in the same error shape. The trade-off: attributes are simple and visible in OpenAPI; code-based validators are more expressive.
"I split validation into two layers. Input validation answers 'is this request well formed?': required fields, lengths, ranges, formats. That belongs at the edge, on the request DTO. Business validation answers 'is this allowed right now?': is the product in stock, is the email already taken, can this order still be cancelled. That belongs in the application or domain layer, next to the data.
For input I start with DataAnnotations on records, plus
IValidatableObjectfor cross-field rules like 'end date after start date'. In controllers, model binding runs validation intoModelState, and[ApiController]short-circuits with a 400ValidationProblemDetailslisting errors per field, so the action never runs with invalid input. Minimal APIs didn't have that until .NET 10: nowbuilder.Services.AddValidation()source-generates validators for the types used as parameters and returns the same ProblemDetails 400, including for nested objects and collections. For rules that are conditional, depend on configuration or need a database lookup, I use FluentValidation, but I callIValidator<T>.ValidateAsyncexplicitly or wrap it in an endpoint filter; the old auto-validation package is deprecated because async rules ran synchronously inside the MVC pipeline.The mistake I see is pushing business rules into attributes or validators that hit the database, so every validation becomes a query and the rule lives in two places. The senior goal is one error contract: whether a field is too long or the product is discontinued, the client gets a
ValidationProblemDetailswith the field name and a message."
| Mechanism | Where it runs | Best for |
|---|---|---|
| DataAnnotations | Model binding (MVC) or AddValidation() (Minimal APIs) |
Simple per-field rules, visible in OpenAPI |
IValidatableObject |
Same | Cross-field rules on one DTO |
| FluentValidation | Your code or a filter | Conditional, collection and async rules |
| Domain/application checks | Handler or domain model | Business invariants |
| Input validation | Business validation | |
|---|---|---|
| Question | Is the request well formed? | Is it allowed now? |
| Example | Quantity between 1 and 100 | Enough stock for 40 units |
| Needs data store? | No | Usually |
| Status code | 400 | 400, 409 or 422 (be consistent) |
| Where | DTO attributes / validators | Application service, domain |
Moving FluentValidation calls that queried the database for uniqueness out of validators and into the command handler removed one extra SQL round trip per request (about 3–5 ms each) and fixed a race where two concurrent requests both passed the 'email is unique' validator; the unique index plus a 409 on DbUpdateException became the single source of truth.
Checks whether the candidate validates in the right places and gives clients a consistent error contract.
Green flags
[ApiController] automatic 400 and .NET 10 AddValidation().Red flags
Model binding ─► ObjectModelValidator walks the bound object graph
─► DataAnnotations attributes + IValidatableObject.Validate
─► errors added to ModelState (key = property path, e.g. "Lines[0].Quantity")
─► [ApiController]: ModelStateInvalidFilter returns 400 ValidationProblemDetails
Validation is recursive over properties and collections, up to MvcOptions.MaxValidationDepth (32). Non-nullable reference types are treated as [Required] when nullable context is enabled (SuppressImplicitRequiredAttributeForNonNullableReferenceTypes controls it).
builder.Services.AddValidation() registers a validation endpoint filter. A source generator (part of the Microsoft.AspNetCore.App framework analysers) finds types used as handler parameters that have validation attributes, and emits validation code, so it works with trimming and Native AOT. Errors are returned through IProblemDetailsService as a 400. You can opt out per endpoint with .DisableValidation(). It validates query, header and body parameters, nested types and collections, and supports IValidatableObject and custom ValidationAttributes.
Validators are classes deriving from AbstractValidator<T> with rules like RuleFor(x => x.Email).NotEmpty().EmailAddress(). Recommended integration today:
IValidator<T> and call ValidateAsync in the handler, then return TypedResults.ValidationProblem(result.ToDictionary()); orValidationFilter<T> that resolves IValidator<T> and short-circuits.The FluentValidation.AspNetCore auto-validation hooked into MVC's synchronous validation pipeline, so async rules couldn't run properly; it is deprecated.
Business rules need current state and often concurrency control. A validator that checks 'email not taken' with a query has a race window; the database unique constraint is the real guard. Domain methods (order.Cancel()) enforce invariants and return or throw domain errors that the API maps to ProblemDetails.
ValidationProblemDetails (RFC 9457 shape) has type, title, status, errors (dictionary of field → messages) and, from ASP.NET Core, a traceId extension. Use it for both input and business errors so clients have one parser.
[Range(1, 100)] to a Minimal API DTO without AddValidation(), post 500, then add it and compare.IValidatableObject for a date range and check the error key.ValidationFilter<T> for FluentValidation and apply it to a route group.maxLength/minimum appear.DataAnnotations with .NET 10 Minimal API validation, a FluentValidation rule called explicitly, and a business rule returning the same error shape.
// Program.cs
using System.ComponentModel.DataAnnotations;
using FluentValidation;
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
builder.Services.AddValidation(); // .NET 10: validates DataAnnotations on parameters
builder.Services.AddScoped<IValidator<CreateBooking>, CreateBookingValidator>();
builder.Services.AddScoped<IBookingService, BookingService>();
var app = builder.Build();
app.MapPost("/bookings", async Task<Results<Created<BookingDto>, ValidationProblem, Conflict<string>>> (
CreateBooking cmd, IValidator<CreateBooking> validator, IBookingService bookings, CancellationToken ct) =>
{
// DataAnnotations already ran (400 before we get here). FluentValidation for conditional rules:
var result = await validator.ValidateAsync(cmd, ct);
if (!result.IsValid) return TypedResults.ValidationProblem(result.ToDictionary());
// Business rule: needs current state, lives in the service, same error contract
return await bookings.CreateAsync(cmd, ct) switch
{
BookingResult.Created c => TypedResults.Created($"/bookings/{c.Booking.Id}", c.Booking),
BookingResult.RoomUnavailable => TypedResults.ValidationProblem(new Dictionary<string, string[]>
{ [nameof(cmd.RoomId)] = ["The room is not available for those dates."] }),
_ => TypedResults.Conflict("Booking could not be created.")
};
});
app.Run();
// Input validation on the DTO: visible in OpenAPI, runs before the handler
public sealed record CreateBooking(
[Range(1, int.MaxValue)] int RoomId,
[Required, EmailAddress, StringLength(254)] string Email,
DateOnly CheckIn,
DateOnly CheckOut,
[Range(1, 6)] int Guests) : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (CheckOut <= CheckIn)
yield return new("Check-out must be after check-in.", [nameof(CheckOut)]);
}
}
// Conditional rule that would be awkward as attributes
public sealed class CreateBookingValidator : AbstractValidator<CreateBooking>
{
public CreateBookingValidator() =>
RuleFor(x => x.CheckOut).Must((cmd, checkOut) => checkOut.DayNumber - cmd.CheckIn.DayNumber <= 28)
.WithMessage("Bookings longer than 28 nights must be made by phone.");
}
public sealed record BookingDto(int Id, int RoomId);
public abstract record BookingResult
{
public sealed record Created(BookingDto Booking) : BookingResult;
public sealed record RoomUnavailable : BookingResult;
}
public interface IBookingService { Task<BookingResult> CreateAsync(CreateBooking cmd, CancellationToken ct); }
AddValidation(); earlier versions never validated. Instead: Register it and test an invalid request.ModelState.IsValid manually in every [ApiController] action. Why it is wrong: The filter already returned 400; the check is dead code. Instead: Remove it and customise InvalidModelStateResponseFactory once if needed.SELECT ... WHERE Email = @e, both see no row, both pass validation and both insert, so you get duplicates or an unhandled DbUpdateException from the index. Instead: Enforce with a unique index and map the violation to a 409 or a field error.ValidateAsync or from a filter.ValidationProblemDetails for both.The senior answer is about placement and contract, not libraries. Input validation is cheap and belongs at the edge so invalid requests never reach your handlers; business invariants belong where the state is, with the database as the final guard against races. The framework now covers the common case in both models ([ApiController] and .NET 10 AddValidation()), so FluentValidation is a choice for expressiveness, not a necessity.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
DataAnnotations + AddValidation() / [ApiController] |
Most DTOs | Limited expressiveness | Complex conditional rules |
| FluentValidation (explicit) | Conditional, collection, config-driven rules | Extra dependency, rules not in OpenAPI | Simple required/range checks |
| Domain invariants | Business rules, state transitions | More modelling | Pure format checks |
| Database constraints | Uniqueness, referential integrity | Exception mapping | As the only validation (poor messages) |
In MVC, a controller is a class whose public methods are actions; each action becomes an endpoint and returns an action result (IActionResult, or ActionResult<T> for a typed body plus status codes). API controllers derive from ControllerBase; Controller adds view support. [ApiController] makes API behaviour explicit: attribute routing is required, an invalid ModelState returns an automatic 400 ValidationProblemDetails, binding sources are inferred (complex types from the body), and error status codes become ProblemDetails. For server-rendered UI there are two styles: MVC with Razor Views (a controller picks a .cshtml view) and Razor Pages (a .cshtml page with its own PageModel and OnGet/OnPost handlers). Razor Pages fits page-per-task, form-heavy apps; MVC fits when one controller serves many views or shares logic with APIs.
Both sit on the same foundation: endpoint routing, middleware, DI, authentication and OpenAPI. The difference is the programming model. Minimal APIs map handlers directly with MapGet/MapPost, organise with route groups, return TypedResults, use endpoint filters, support Native AOT, and in .NET 10 get built-in DataAnnotations validation with AddValidation(). Controllers group actions in classes and bring the full MVC feature set: [ApiController] behaviours (automatic 400s, binding inference), the five MVC filter types, custom model binders, input/output formatters with content negotiation and JSON Patch. For a new API service I default to Minimal APIs organised by feature; I choose controllers when the team relies on MVC filters, formatters or existing conventions. The trade-off is less ceremony and AOT versus a richer, more conventional framework.
Last updated 23 Nov 2026.