Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 52 ยท Models, Validation and Serialization

Model Validation

Validate API input in ASP.NET Core with data annotations, IValidatableObject, custom attributes, endpoint filters and the .NET 10 minimal API validation.

Binding only checks that a request can be converted to your parameter types. A body of {"name":"","age":-5} converts perfectly well to a Signup record, and your code would happily create a user with no name and a negative age. Validation is the step that asks whether the values that arrived are acceptable. It is your first line of defense against bad data, and it gives clients a precise list of what to fix.

In this lesson you will use data annotations (attributes such as [Required] and [Range]), run them by hand with the Validator class, write a custom attribute and an IValidatableObject, and plug validation into minimal APIs with an endpoint filter. We finish with the built-in minimal API validation that arrived in .NET 10 and what it needs from the build. For the general C# side, see Validation and Contracts.

Where validation sits

flowchart LR
    A["Request"] --> B["Binding<br/>text to objects"]
    B -->|"cannot convert"| X["400 Bad Request"]
    B --> C["Validation<br/>rules on values"]
    C -->|"rules broken"| Y["400 with error list"]
    C --> D["Your handler<br/>business logic"]
    D -->|"business rule fails"| Z["409 or 422"]
    D --> E["200 / 201"]

Validation checks shape and format; rules that need your data (such as "email already used") belong in the handler.

Keep that last split in mind. Validation attributes check things that can be decided from the object alone: required, length, range, format, relations between its own fields. Anything that needs a database or another service is a business rule and is answered from your handler, usually with 409 Conflict or 422 Unprocessable Entity.

Data annotations

The System.ComponentModel.DataAnnotations namespace has the attributes you will use most:

Attribute Checks
[Required] Not null; for strings also not empty (AllowEmptyStrings = false by default)
[StringLength(50, MinimumLength = 2)] String length bounds
[MinLength], [MaxLength] Minimum or maximum length of strings and collections
[Range(18, 120)] A number or other comparable value lies between two bounds
[EmailAddress], [Url], [Phone] A simple format check (not proof the address exists)
[RegularExpression("^[A-Z]{3}$")] A pattern
[Compare("Other")] Equal to another property

The attributes only describe rules. Something has to run them. In MVC that is automatic; in minimal APIs you run them yourself, with a filter, or (on .NET 10) with the built-in support described later. The runner is the static Validator class.

With a positional record such as record Signup(string Name, int Age), an attribute written on a parameter lands on the parameter, not the property, and the validator looks at properties. Write [property: Required] so it is attached where validation can see it.

C# Running data annotations by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Each failed rule becomes a ValidationResult with a list of member names and a message. Note that the empty name produced exactly one message even though it breaks two rules: for a single property, Validator stops at the first failing attribute when [Required] fails. You can replace the default text with ErrorMessage = "Please enter your name" on any attribute.

Custom attributes and IValidatableObject

When a rule is not built in, you have two options.

A custom attribute derives from ValidationAttribute and overrides IsValid. It is reusable across types and attaches to the one property it guards.

IValidatableObject puts a Validate method on the type itself. It is the right place for rules that compare several properties (check-out must be after check-in). It receives a ValidationContext, whose GetService method gives access to registered services if the rule needs them.

C# A custom attribute plus a cross-field rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first booking shows two property-level errors but not the date-order error. The second booking passes its property rules, so Validate runs and finds the object-level problem. That is how Validator works: IValidatableObject.Validate is only called when all attribute-based checks have passed. If you want every message at once, write cross-field checks in the same place or run both explicitly.

Validating minimal API input with a filter

A minimal API does not run annotations for you in older versions (and in .NET 10 only with a build-time feature described below). The classic solution is an endpoint filter (Endpoint Filters) that finds the argument, validates it and short-circuits with a standard validation problem response before your handler runs.

Results.ValidationProblem(errors) builds an RFC 9457 application/problem+json response with status 400 and an errors dictionary that maps each member name to its messages. That is the same shape MVC controllers return, so clients can use one parser.

C# A reusable validation filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The filter is generic, so one line (.WithValidation<Signup>()) protects any endpoint, and putting it on a route group applies it to every endpoint in the group (Route Groups). It runs after binding, so a body that cannot even be parsed still gets the framework's plain 400 first.

Built-in validation in .NET 10

.NET 10 added validation support to minimal APIs themselves. You call builder.Services.AddValidation() once, and the framework validates bound parameters (including the members of records and nested objects) against their data annotation attributes and IValidatableObject, answering with the same validation problem shape. You can switch it off for one endpoint with DisableValidation().

C#
// Program.cs (real project; read-only here)
builder.Services.AddValidation();

app.MapPost("/signup", (Signup signup) => Results.Created($"/users/{signup.Name}", signup));

record Signup(
    [Required, StringLength(40, MinimumLength = 2)] string Name,
    [EmailAddress] string Email,
    [Range(18, 120)] int Age);

This feature finds the validatable types at compile time, through a source generator that ships with the web SDK. Our single-file runner has no source generators, and when we tried it there, AddValidation() compiled and ran but validated nothing: an invalid body returned 200. That is the real behavior of the feature without its generator, and a good reminder: after you enable validation in a real project, send an invalid request and check that you get a 400. Until you do, treat "no errors" with suspicion.

Validate at the edge of your system, once. Controllers and minimal APIs validate request models; services should still guard their own invariants (a constructor that rejects a negative price), because a service can be called from places that never saw the HTTP request.

Practical advice

  • Use specific error messages that tell the client how to fix the problem ("Age must be between 18 and 120"), and leave out internal details.
  • Do not trust client-side validation. It is a convenience for users; the server must enforce every rule.
  • Keep request models separate from entities. Validation attributes on a request DTO describe what you accept from a client, which is often different from what you store (DTOs, Records and Mapping).
  • Combine with strict JSON. Rejecting unknown properties and validating values together close most mass-assignment holes (JSON Serialization in APIs).
  • Return the same error shape everywhere. ValidationProblem and problem details (Error Handling and Problem Details) let clients handle failures generically.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A request body parses correctly into your record, but the age is -5. Which step is responsible for rejecting it?

    Binding only converts text into objects. Validation checks whether the converted values satisfy rules such as [Range].
  2. 2. Why do you write [property: Required] on a positional record parameter?

    By default an attribute on a record parameter targets the parameter. The property: target puts it on the generated property, where Validator.TryValidateObject looks.
  3. 3. When is IValidatableObject.Validate called by Validator.TryValidateObject?

    Validator first runs the property attributes. The object-level Validate method runs only when those succeed, which is why a cross-field error can appear only after you fix the property errors.
  4. 4. Which response does Results.ValidationProblem(errors) produce?

    ValidationProblem returns status 400 with an RFC 9457 problem details body whose errors member maps each field name to its messages.
  5. 5. Why should you test an invalid request after calling AddValidation() in a project?

    The .NET 10 minimal API validation discovers types through generated code. If that generation is not part of the build, requests pass through unvalidated, so verify with a bad request.

Summary

  • Binding converts input; validation decides whether the values are acceptable; business rules that need data belong in the handler.
  • Data annotations ([Required], [Range], [StringLength], [EmailAddress], ...) describe rules, and Validator.TryValidateObject runs them.
  • Put attributes on the property ([property: ...] for positional records); write custom rules as ValidationAttribute classes or IValidatableObject, which runs only after property checks pass.
  • An endpoint filter plus Results.ValidationProblem gives minimal APIs a reusable 400 response with a field-to-messages dictionary.
  • .NET 10's AddValidation() does this for you but relies on a source generator in the build; always test with an invalid request.

Next: DTOs, Records and Mapping