Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 52 ยท MVC, Controllers and Razor

Model Binding and Filters in MVC

How MVC binds request data to action parameters, how ModelState and the automatic 400 work, and how action, exception and result filters run in order.

Before a controller action can run, the framework has to turn an HTTP request, which is only text, into the typed arguments your method declares. That conversion is model binding. Afterwards the arguments are checked, and the outcome is recorded in an object called ModelState. Around the action itself there is a second mechanism, filters, which let you run code before and after actions, results and exceptions without touching the actions.

Binding and filters are the two ideas that make controllers feel different from minimal APIs. This lesson shows where binding gets its data, how ModelState and the automatic 400 work, what changes if you leave [ApiController] off, and how the five filter kinds are ordered. It builds directly on Controllers and Actions; the minimal API equivalents are in Parameter Binding and Endpoint Filters.

Binding sources

Every parameter is filled from one binding source. You can name it with an attribute, and [ApiController] infers it when you do not.

Attribute Reads from Notes
[FromRoute] Route values such as Inferred for parameters that match a route token
[FromQuery] Query string (?page=2) Inferred for simple types
[FromHeader] A request header Name = "X-Client" gives the header name
[FromBody] The request body, via input formatters (JSON) Inferred for complex types; only one per action
[FromForm] application/x-www-form-urlencoded or multipart form Inferred for IFormFile
[FromServices] The dependency injection container Inferred for registered service types
flowchart TD
    R["HTTP request"] --> A["Route values"]
    R --> B["Query string"]
    R --> C["Headers"]
    R --> D["Body (JSON or form)"]
    S["DI container"] --> P
    A --> P["Action parameters"]
    B --> P
    C --> P
    D --> P
    P --> M["ModelState<br/>values + errors"]

Each parameter has one source; everything that went wrong is collected in ModelState.

C# Binding from route, query, header, body and services

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.

Study the second and third requests. The missing header and the broken values never reach your code: every problem is listed under its own key in a 400 response. Two details are worth knowing. First, MVC treats a non-nullable reference type (string client) as implicitly required when nullable reference types are enabled, which is why the missing header failed; declare string? client to make it optional. Second, a missing non-nullable value type (int page) is not an error: it silently becomes 0. Use int? page, a default value, or [BindRequired] when absence matters.

Records used as request models should carry validation attributes on their constructor parameters, as above. MVC refuses to start when it finds validation attributes on the generated properties of a positional record (the [property: ...] form used with Validator in the Model Validation lesson), and its error message says so.

ModelState and the automatic 400

While binding, MVC fills a ModelStateDictionary (available as ModelState on the controller). It holds the raw and converted values and a list of errors per key. Binding errors (a string where an int was expected) and validation errors (broken data annotations) both end up there. ModelState.IsValid is true only when there are none.

With [ApiController], a filter checks ModelState before your action, and answers 400 itself if it is invalid, as the previous example showed. Without [ApiController], you do that check yourself. That is useful to understand because it shows exactly what the attribute is saving you.

C# Checking ModelState yourself, without [ApiController]

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 same dictionary received both the attribute errors and the one you added with AddModelError, and ValidationProblem(ModelState) can turn it into the standard problem response in a single call. Adding errors for rules that need your data, such as the duplicate title, is the usual way to keep the response format consistent.

If you do want [ApiController] but want to take over the 400, you can disable the automatic filter in AddControllers().ConfigureApiBehaviorOptions(o => o.SuppressModelStateInvalidFilter = true), or customize the response with InvalidModelStateResponseFactory.

Filters

A filter is code that MVC runs at fixed points around an action. Filters are the tool for cross-cutting concerns that apply to many actions: authorization, logging, caching headers, translating exceptions, wrapping results. There are five kinds, in the order they run:

  1. Authorization filters run first and decide whether the request may continue ([Authorize] is one).
  2. Resource filters wrap almost everything, including model binding; they suit caching and short-circuiting early.
  3. Action filters run immediately before and after the action method (OnActionExecuting, OnActionExecuted), after binding.
  4. Exception filters handle exceptions thrown by actions and action filters.
  5. Result filters run before and after the result (the Ok(...) object) is executed, which is when the body is written.
flowchart LR
    A["Authorization"] --> B["Resource<br/>(before)"]
    B --> C["Model binding"]
    C --> D["Action filter<br/>(before)"]
    D --> E["Action method"]
    E --> F["Action filter<br/>(after)"]
    F --> G["Result filter<br/>(before)"]
    G --> H["Result executes"]
    H --> I["Result filter (after)<br/>Resource filter (after)"]
    E -. "throws" .-> X["Exception filter"]

Filters form nested layers; an exception from the action jumps to the exception filters.

Order inside one kind

When several filters of the same kind apply, they form a pipeline layered by scope. On the way in, the outermost scope goes first: global (registered in AddControllers(options => options.Filters.Add(...))), then controller (an attribute on the class), then action (an attribute on the method). On the way out, the order is reversed, like nested function calls. Within the same scope, use the Order property (lower runs first) because attribute order from reflection is not guaranteed.

A filter can short-circuit by setting context.Result in an "executing" method. The action is skipped, and the filters that had already started still get their "executed" call, with Canceled set to true.

C# Filter order, an exception filter and a short circuit

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 trace makes the layering visible. For /demo/ok, the "before" lines go global, controller, action; the "after" lines run in exactly the opposite order. For /demo/fail, the exception travels outward through the action filters (which see it in context.Exception), and the exception filter converts it into a 409 response. Because that result came from an exception filter, the result filter never runs, which is why no X-Served-By header appears. In /demo/secret without the key, RequireKey sets the result and the body of the action never runs; every filter that had already started reports canceled.

Writing and registering filters

  • Attribute filters derive from ActionFilterAttribute, ResultFilterAttribute or ExceptionFilterAttribute and are applied with [...], as above. They are created by the attribute system, so they cannot take constructor dependencies from DI.
  • [ServiceFilter(typeof(MyFilter))] and [TypeFilter(typeof(MyFilter))] create the filter through DI, so the class can inject services. ServiceFilter requires you to register the type; TypeFilter does not.
  • Global filters are added in AddControllers(options => options.Filters.Add<MyFilter>()) and affect every action.
  • Implement IAsyncActionFilter (one OnActionExecutionAsync method with a next delegate) when the filter needs to await something.

Filters see only MVC requests. Static files, endpoints mapped with MapGet and anything that happens before routing never pass through them. For code that must cover every request, use middleware. Choose filters when you need access to MVC concepts such as the action, ModelState or the action result.

Practical advice

  • Rely on the binding-source inference of [ApiController], but state [FromBody], [FromQuery] and so on explicitly when a parameter list is ambiguous or you want readers to see the contract.
  • Make optional input nullable or give it a default. Non-nullable reference types are implicitly required; missing non-nullable value types silently become their default.
  • Bind to request DTOs, not entities, to avoid over-posting (DTOs, Records and Mapping).
  • Use filters for cross-cutting rules, not business logic. If a rule changes how data is processed, put it in a service.
  • Keep filters fast and stateless. They run on every matching request; avoid storing per-request state in fields, because filters registered by type may be shared.
  • Prefer exception handling middleware for the app-wide last resort (Error Handling and Problem Details) and exception filters for translating specific exceptions into specific results.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which binding source does [ApiController] infer for a complex type parameter such as ItemDto?

    Complex types are inferred as [FromBody], simple types come from route or query, and service types come from DI.
  2. 2. A [FromQuery] int page parameter is missing from the request. What happens by default?

    Missing non-nullable value types silently take their default value. Make the parameter nullable, give it a default, or add [BindRequired] to require it.
  3. 3. You remove [ApiController] from a controller. What changes for an invalid model?

    The automatic 400 comes from [ApiController]. Without it, binding and validation still record errors in ModelState, but your action must inspect them.
  4. 4. A global action filter, a controller-level one and an action-level one all apply. In which order do their OnActionExecuting methods run?

    On the way in the outermost scope goes first: global, then controller, then action. OnActionExecuted runs in the reverse order.
  5. 5. What does a filter do when it sets context.Result inside OnActionExecuting?

    Setting the result short-circuits the pipeline. The action method is skipped, and filters that had already started still receive their executed call with Canceled set to true.

Summary

  • Model binding fills each action parameter from one source: route, query, header, body, form or services; [ApiController] infers the source from the parameter type.
  • Binding and validation problems are collected in ModelState; [ApiController] turns an invalid state into an automatic 400 before your action runs, and without it you check ModelState.IsValid yourself.
  • Non-nullable reference types are implicitly required, while missing value types become their default unless made nullable or [BindRequired].
  • Filters run in layers: authorization, resource, action, exception and result; within a kind they nest global, controller, action on the way in and reverse on the way out.
  • A filter can short-circuit by setting context.Result; use ServiceFilter or TypeFilter when a filter needs dependency injection.
  • Use filters for MVC-level cross-cutting concerns and middleware for anything that must cover every request.

Next: Razor Views and Razor Pages Overview