What is model binding in ASP.NET Core, and what are the binding sources?
Quick Answer
Model binding maps values from the HTTP request onto your action's parameters. Sources: [FromRoute], [FromQuery], [FromBody] (JSON, one per action), [FromForm], [FromHeader], and [FromServices] (DI). With [ApiController], the source is inferred — complex types from the body, simple types from route/query.
Model binding is the framework taking the request — route values, query string, JSON body, form fields, headers — and populating my action parameters, converting the strings to the right types along the way. The sources are the [From*] attributes, and with [ApiController] they're inferred: complex types come from the body, simple ones from the route or query. The thing to be careful about is over-posting — if I bind straight to my EF entity, a caller could set a field they shouldn't. So I bind to a request DTO that only exposes the fields the endpoint should accept.
- The binder walks the parameter's properties and looks for matching keys in the chosen source, converting strings to the target types.
- After binding, validation runs and populates
ModelState. - Over-posting — a caller sends
IsAdmin=trueand it binds to your entity. Fix: bind to a purpose-built request/DTO with only the allowed fields, not the EF entity. [Bind]/[BindNever]can include/exclude properties (MVC).- Custom binders (
IModelBinder) handle non-standard formats — e.g. a comma-separated list in a query param.