Model Binding & Validation
Model binding is the step where ASP.NET Core turns the raw HTTP request — route values, query string, headers, form fields, JSON body — into the typed parameters of your action or endpoint. Validation then checks those values against rules you declare, so your code only ever sees sensible input.
Where values come from
By default the framework looks in a fixed set of sources. You can be explicit with attributes:
| Attribute | Source | Example |
|---|---|---|
[FromRoute] |
Route template values | /orders/{id} |
[FromQuery] |
Query string | ?page=2&size=20 |
[FromBody] |
Request body (JSON) | {"name":"Ana"} |
[FromForm] |
Form fields (application/x-www-form-urlencoded or multipart) |
HTML <form> posts |
[FromHeader] |
Request header | X-Correlation-Id |
[FromServices] |
Dependency injection container | IEmailSender |
In an [ApiController], simple types (int, string, Guid, DateOnly…) are bound from the route or query, complex types from the JSON body — so attributes are usually only needed for headers, forms and edge cases.
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
[HttpGet]
public IActionResult Search(
[FromQuery] string? status,
[FromQuery] int page = 1,
[FromHeader(Name = "X-Client")] string? client = null)
=> Ok(new { status, page, client });
}$ curl -s "localhost:5000/api/orders?status=shipped&page=3" -H "X-Client: mobile"
$ curl -s "localhost:5000/api/orders"{"status":"shipped","page":3,"client":"mobile"}
{"status":null,"page":1,"client":null}
If a value can't be converted — ?page=abc for an int — binding records an error in ModelState instead of throwing.
Declaring rules with Data Annotations
Validation rules are attributes from System.ComponentModel.DataAnnotations placed on the properties of your input model:
using System.ComponentModel.DataAnnotations;
public class RegisterRequest
{
[Required, StringLength(30, MinimumLength = 3)]
public string UserName { get; set; } = "";
[Required, EmailAddress]
public string Email { get; set; } = "";
[Range(13, 120)]
public int Age { get; set; }
[Compare(nameof(Email), ErrorMessage = "Emails do not match.")]
public string ConfirmEmail { get; set; } = "";
}| Attribute | Checks |
|---|---|
[Required] |
Not null (and, for strings, not empty) |
[StringLength(max, MinimumLength = n)] |
String length range |
[Range(min, max)] |
Numeric (or date) range |
[EmailAddress], [Phone], [Url] |
Format of common values |
[RegularExpression(pattern)] |
Custom pattern |
[Compare(other)] |
Equals another property |
The same validator ASP.NET Core uses is part of the base library, so we can run it directly:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
var input = new RegisterRequest { UserName = "jo", Email = "jo-at-example", Age = 9, ConfirmEmail = "jo@example.com" };
var errors = new List<ValidationResult>();
bool valid = Validator.TryValidateObject(input, new ValidationContext(input), errors, validateAllProperties: true);
Console.WriteLine(quot;Valid: {valid}");
foreach (var e in errors)
Console.WriteLine(quot;- {string.Join(",", e.MemberNames)}: {e.ErrorMessage}");
class RegisterRequest
{
[Required, StringLength(30, MinimumLength = 3)]
public string UserName { get; set; } = "";
[Required, EmailAddress]
public string Email { get; set; } = "";
[Range(13, 120)]
public int Age { get; set; }
[Compare(nameof(Email), ErrorMessage = "Emails do not match.")]
public string ConfirmEmail { get; set; } = "";
}Valid: False
- UserName: The field UserName must be a string with a minimum length of 3 and a maximum length of 30.
- Email: The Email field is not a valid e-mail address.
- Age: The field Age must be between 13 and 120.
- ConfirmEmail: Emails do not match.
Automatic 400 responses
With [ApiController], an action never runs when ModelState is invalid. The framework returns a ValidationProblemDetails response for you, with errors grouped by property:
$ curl -s -X POST localhost:5000/api/users -H "Content-Type: application/json" -d '{"userName":"jo","email":"jo@example.com","age":30,"confirmEmail":"jo@example.com"}'{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"UserName":["The field UserName must be a string with a minimum length of 3 and a maximum length of 30."]},"traceId":"00-8e2d4f6a1b3c5d7e9f0a2b4c6d8e0f12-3a5c7e9b1d2f4a6c-00"}
Without [ApiController] (for example in an MVC controller returning views) you check it yourself:
[HttpPost]
public IActionResult Register(RegisterRequest model)
{
if (!ModelState.IsValid)
return View(model); // redisplay the form with error messages
// ... save the user
return RedirectToAction("Welcome");
}Custom rules
For rules that involve several properties, implement IValidatableObject. Its Validate method runs after the attribute checks pass:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
var booking = new Booking { Guests = 2, CheckIn = new DateOnly(2026, 11, 10), CheckOut = new DateOnly(2026, 11, 8) };
var errors = new List<ValidationResult>();
Validator.TryValidateObject(booking, new ValidationContext(booking), errors, true);
foreach (var e in errors)
Console.WriteLine(quot;{string.Join("+", e.MemberNames)}: {e.ErrorMessage}");
class Booking : IValidatableObject
{
[Range(1, 6)]
public int Guests { get; set; }
public DateOnly CheckIn { get; set; }
public DateOnly CheckOut { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (CheckOut <= CheckIn)
yield return new ValidationResult("Check-out must be after check-in.", new[] { nameof(CheckIn), nameof(CheckOut) });
}
}CheckIn+CheckOut: Check-out must be after check-in.
Note: Minimal APIs in .NET 9 do not validate Data Annotations automatically (built-in minimal API validation arrived in .NET 10). Use an endpoint filter that calls
Validator.TryValidateObjectand returnsResults.ValidationProblem(...), or a library such as FluentValidation.
Tip: Bind to dedicated request models (DTOs), never directly to your database entities. Otherwise a client can set fields you never meant to expose, such as
IsAdmin— a problem known as over-posting.
Test yourself
In an [ApiController], where is a complex-type parameter like CreateOrder order bound from by default?
- The query string
- Form fields
- The JSON request body
- Route values
What happens when a request to an [ApiController] action fails validation?
- The action runs with
ModelState.IsValid == false - A 400 ValidationProblemDetails response is returned automatically
- An exception is thrown and a 500 is returned
- The invalid properties are set to null and the action runs
Which interface lets a model validate rules that span several properties?
- IValidatableObject
- IModelBinder
- IComparable
- IActionFilter