Model binding in ASP.NET Core: the binding source attributes, how controllers with [ApiController] and Minimal APIs infer sources for simple types, complex types, services and special types, the one-body rule, [AsParameters] parameter objects, and what happens when binding fails.
Model binding takes data from the request (route values, query string, headers, form fields, the JSON body) and from DI, converts it, and passes it to your handler's parameters. You can be explicit with [FromRoute], [FromQuery], [FromHeader], [FromForm], [FromBody] and [FromServices], or let the framework infer. In Minimal APIs: a parameter named in the route template comes from the route, other simple types from the query, registered services from DI, and complex types from the JSON body. In controllers with [ApiController]: complex types from the body, IFormFile from the form, route names from the route, the rest from the query. Only one parameter can read the body. [AsParameters] groups parameters into a record. The trade-off: inference keeps code short, but explicit attributes make the contract obvious in reviews and OpenAPI.
"Model binding is the step that turns an HTTP request into typed method parameters. The framework looks at each parameter, decides where its value comes from, reads it as a string or stream, converts it, and passes it in. The sources are route values, the query string, headers, form fields, the request body, and the DI container.
You can always say where a value comes from with
[FromRoute],[FromQuery],[FromHeader],[FromForm],[FromBody]or[FromServices]. When you don't, each model infers. Minimal APIs look at the route template first: ifidappears in/orders/{id}, it's a route value. Other simple types, meaning anything with aTryParse, come from the query. If the type is registered in DI, it's a service. Special types likeHttpContext,CancellationTokenandClaimsPrincipalare injected directly. Any remaining complex type is read from the JSON body. Controllers with[ApiController]are similar: complex types from the body,IFormFilefrom the form, names in the route template from the route, everything else from the query. Without[ApiController], complex types bind from form and query instead, which surprises people. Only one parameter can come from the body, because the body is a stream you read once. When a handler has lots of query parameters, I use[AsParameters]with a record so the signature stays readable.The mistake I see is relying on inference in a way that silently changes behaviour, like registering a type in DI that was previously bound from the body. I'm explicit on public contracts. Binding is part of your API contract, so I make the source obvious."
| Attribute | Reads from | Typical use |
|---|---|---|
[FromRoute] |
Route values | /orders/{id} |
[FromQuery] |
Query string | ?page=2&size=50 |
[FromHeader] |
Request headers | X-Correlation-Id, If-Match |
[FromForm] |
Form fields and files | HTML forms, IFormFile |
[FromBody] |
Request body (JSON by default) | Commands, DTOs |
[FromServices] / [FromKeyedServices] |
DI container | Services in handlers or actions |
[AsParameters] (Minimal APIs) |
Members bound individually | Grouping many parameters |
| Parameter | Minimal APIs | [ApiController] controllers |
|---|---|---|
| Name matches route template | Route | Route |
Simple type (has TryParse) |
Query | Query |
| Registered DI service | Service | Needs [FromServices] (inferred for registered services since .NET 7) |
| Complex type | JSON body | JSON body |
IFormFile / IFormFileCollection |
Form | Form |
HttpContext, CancellationToken, ClaimsPrincipal |
Special binding | Via HttpContext or parameters |
A search endpoint with 11 query parameters became ([AsParameters] ProductSearch search, IProductStore store, CancellationToken ct). The OpenAPI document didn't change, the handler went from a 15-line signature to 3 parameters, and adding a new filter became a one-line change to the record.
Checks that the candidate knows where each parameter value comes from and why binding sometimes 'mysteriously' fails.
Green flags
[AsParameters], special types and the Content-Type requirement.Red flags
[ApiController] changes.Request ─► Routing (route values) ─► Endpoint
│
Minimal API: generated RequestDelegate binds each parameter, then calls handler
MVC: action invoker ─► model binders + value providers ─► ModelState ─► action
RequestDelegateFactory (runtime) or the Request Delegate Generator (compile time) emits code per parameter: read RouteValues["id"], call int.TryParse, or ReadFromJsonAsync<T>. No ModelState.SimpleTypeModelBinder, ComplexObjectModelBinder, BodyModelBinder, FormFileModelBinder) build objects and record errors in ModelState.A type is "simple" if it can be converted from a single string: primitives, Guid, DateTime, enums, and any type with static bool TryParse(string, out T) (or IParsable<T>). Complex types in Minimal APIs come from the body unless you use [FromQuery] on a type with TryParse, [AsParameters], or BindAsync.
The request body is a forward-only stream. Minimal APIs and BodyModelBinder read it once with System.Text.Json (using JsonOptions, web defaults: camelCase, case-insensitive). A second [FromBody] parameter is an error at start-up in Minimal APIs. Content type matters: Minimal APIs require application/json for body binding and return 415 otherwise.
RouteHandlerOptions.ThrowOnBadRequest (on by default in Development) you get an exception with a clear message instead, which is great for debugging.ModelState; [ApiController] turns invalid ModelState into a 400 ValidationProblemDetails. Without it, the action runs with default values.In Minimal APIs nullability drives "required": int id is required, int? page and string? sort are optional, and parameters with default values are optional.
MapGet("/orders/{id}", (int id, int? page, IOrderStore store) => ...) and test /orders/abc in Development and Production.Content-Type: text/plain to a Minimal API and read the 415.[ApiController] from a controller and post JSON to an action taking a DTO; inspect the bound values.[AsParameters] and diff the OpenAPI document.Explicit and inferred binding in Minimal APIs, [AsParameters], and the controller equivalent.
// Program.cs
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IProductStore, SqlProductStore>();
builder.Services.AddControllers();
var app = builder.Build();
// id: route (name in template); includeArchived: query (simple type); store: DI; ct: special
app.MapGet("/products/{id:int}", async (int id, bool includeArchived, IProductStore store, CancellationToken ct) =>
await store.FindAsync(id, includeArchived, ct) is { } p ? Results.Ok(p) : Results.NotFound());
// Complex type with no attribute: JSON body. Header made explicit because it's part of the contract.
app.MapPost("/products", async (CreateProduct cmd, [FromHeader(Name = "Idempotency-Key")] string? key,
IProductStore store, CancellationToken ct) =>
{
var product = await store.AddAsync(cmd, key, ct);
return Results.Created($"/products/{product.Id}", product);
});
// [AsParameters]: each member bound individually (query by default), keeps the signature small
app.MapGet("/products", (
[AsParameters] ProductSearch search, IProductStore store, CancellationToken ct) => store.SearchAsync(search, ct));
app.MapControllers();
app.Run();
public sealed record ProductSearch(string? Q, string? Category, decimal? MinPrice, int Page = 1, int Size = 20);
public sealed record CreateProduct(string Name, decimal Price);
public sealed record Product(int Id, string Name, decimal Price);
public interface IProductStore
{
Task<Product?> FindAsync(int id, bool includeArchived, CancellationToken ct);
Task<Product> AddAsync(CreateProduct cmd, string? idempotencyKey, CancellationToken ct);
Task<IReadOnlyList<Product>> SearchAsync(ProductSearch search, CancellationToken ct);
}
// Controller equivalent: [ApiController] infers [FromRoute] for id and [FromBody] for the DTO
[ApiController]
[Route("api/products")]
public sealed class ProductsController(IProductStore store) : ControllerBase
{
[HttpGet("{id:int}")]
public async Task<ActionResult<Product>> Get(int id, [FromQuery] bool includeArchived, CancellationToken ct)
=> await store.FindAsync(id, includeArchived, ct) is { } p ? p : NotFound();
[HttpGet]
public Task<IReadOnlyList<Product>> Search([FromQuery] ProductSearch search, CancellationToken ct)
=> store.SearchAsync(search, ct); // complex type from the query needs [FromQuery] explicitly
}
[ApiController] read complex types from the body. Instead: Use [FromQuery] (controllers) or [AsParameters] (Minimal APIs).[FromBody] parameters. Why it is wrong: The body is a stream read once; Minimal APIs fail at start-up and MVC only binds one. Instead: Wrap both in one request DTO; other parameters can still come from route, query, headers or DI.[FromForm], so you get a 415. Instead: Add [FromForm] and, for browser forms, handle anti-forgery.[ApiController] and expecting the same behaviour. Why it is wrong: Without it, complex types bind from form and query instead of the body, and an invalid model no longer triggers the automatic 400: the action runs with nulls or default values and only ModelState.IsValid tells you something went wrong. Instead: Keep it on API controllers, or add explicit attributes and check ModelState.Content-Type. Why it is wrong: Minimal APIs return 415; MVC can't find a formatter. Instead: Send application/json and check client defaults.int? id doesn't help if the template needs {id}. Instead: Use {id?} in the template.Binding is part of the API contract, and a senior treats the inference rules as a convenience, not a design. On public APIs, explicit attributes (or [AsParameters] records) make the source visible in code reviews and in the OpenAPI document, and protect you from accidental changes, such as a DTO type later being registered in DI. The framework already gives you good failure behaviour: 400s in Minimal APIs, ModelState in MVC, and very readable exceptions in Development.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Inference | Internal APIs, obvious shapes | Hidden rules | Public contracts with mixed sources |
Explicit [FromX] |
Public APIs, headers, ambiguous cases | Slightly noisier signatures | Trivial handlers |
[AsParameters] record |
Many query/header parameters | One more type | One or two parameters |
Custom BindAsync / model binder |
Your own types from several sources | Code to maintain | When TryParse is enough |
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.
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.
Last updated 23 Nov 2026.