In ASP.NET Core MVC, which filter kinds exist and in what order do they run around a controller action?
answer
- filters run after action selection
- authorization, resource, action, exception, result
- resource filters run before model binding
- exception filters skip result execution
- IAlwaysRunResultFilter
basics
~20 sMVC runs authorization filters, then resource filters, then model binding, then action filters around the action, and result filters around the result's execution. Exception filters catch failures from controller creation to the action, not from result execution.
solid answer
~50 sFilters run inside MVC's action invoker, so only after routing has selected a controller action. **Authorization filters** (`IAuthorizationFilter`) run first and can short-circuit. **Resource filters** (`IResourceFilter`) wrap everything that follows, including model binding, which makes them the place for caching or for disabling form binding. **Action filters** (`IActionFilter`) wrap the action method and see the bound `ActionArguments` and the returned result. **Exception filters** (`IExceptionFilter`) handle unhandled exceptions thrown by controller creation, model binding, action filters or the action, but not by resource filters, result filters or result execution. **Result filters** (`IResultFilter`) wrap the execution of the action result, such as view rendering or JSON serialization, and only run when an action or action filter produced the result; `IAlwaysRunResultFilter` runs even after a short-circuit. Each kind has an `Async` variant, and the before code runs outer-to-inner, the after code in reverse.
code
csharp · 13 linespublic sealed class TraceFilter(ILogger<TraceFilter> log) :
IResourceFilter, IActionFilter, IResultFilter
{
public void OnResourceExecuting(ResourceExecutingContext c) => log.LogInformation("1 resource before (no arguments yet)");
public void OnActionExecuting(ActionExecutingContext c) => log.LogInformation("2 action before: {Args}", c.ActionArguments.Count);
public void OnActionExecuted(ActionExecutedContext c) => log.LogInformation("3 action after");
public void OnResultExecuting(ResultExecutingContext c) => log.LogInformation("4 result before");
public void OnResultExecuted(ResultExecutedContext c) => log.LogInformation("5 result after (response usually started)");
public void OnResourceExecuted(ResourceExecutedContext c) => log.LogInformation("6 resource after");
}
// Program.cs
builder.Services.AddControllers(o => o.Filters.Add<TraceFilter>());go deeper
Name the five filter kinds and recall that authorization runs first and result filters run around the result.
Recite the full order including model binding, explain what each kind can see, and how short-circuiting changes what runs.
Place logic correctly: rendering and serialization errors escape exception filters, middleware rejections skip all filters, always-run result filters cover short-circuits.
Set rules for which cross-cutting concerns live in middleware versus MVC filters so behaviour stays consistent across controllers, pages and Minimal APIs.
## Where filters sit ASP.NET Core processes a request through **middleware** first: HTTPS redirection, authentication, authorization, CORS and so on. Endpoint routing picks the endpoint, and when that endpoint is a controller action, MVC's **action invoker** takes over. Filters run only inside that invoker. A request rejected by middleware, or one that matches no controller, never meets a single MVC filter. ## The five kinds | Kind | Interfaces | Runs | Typical job | |---|---|---|---| | Authorization | `IAuthorizationFilter`, `IAsyncAuthorizationFilter` | first | custom per-action access checks | | Resource | `IResourceFilter`, `IAsyncResourceFilter` | around everything below, before model binding | caching, short-circuiting, controlling binding | | Action | `IActionFilter`, `IAsyncActionFilter` | around the action method, after binding | auditing, argument checks, result tweaks | | Exception | `IExceptionFilter`, `IAsyncExceptionFilter` | when something below throws | translating exceptions into results | | Result | `IResultFilter`, `IAsyncResultFilter`, `IAlwaysRunResultFilter` | around executing the result | headers, view-model tweaks, output wrapping | MVC itself uses these slots: the `[ApiController]` automatic 400 is an action filter (`ModelStateInvalidFilter`, `Order = -2000`), and `[Consumes]` is a resource filter that can return 415. ## The order for one request 1. Authorization filters run. If one sets `context.Result`, the pipeline short-circuits. 2. Resource filters run their *before* code (`OnResourceExecuting`). 3. MVC creates the controller and **binds the action's arguments**. 4. Action filters run their *before* code (`OnActionExecuting`), outermost first. 5. The action method runs. 6. Action filters run their *after* code (`OnActionExecuted`), innermost first. 7. If steps 3 to 6 threw, exception filters get the chance to handle it. 8. Result filters run their *before* code, then the result executes (the view renders or the formatter serializes), then their *after* code. 9. Resource filters run their *after* code (`OnResourceExecuted`). The "outermost first" rule comes from scope and `Order`: global filters wrap controller filters, which wrap action filters, unless an `Order` value says otherwise. ## What each kind cannot see - **Resource filters** run before binding, so they cannot read `ActionArguments`. - **Action filters** do not run when an authorization or resource filter short-circuited. - **Exception filters** do not catch exceptions from resource filters, result filters or result execution. A view that throws while rendering, or a serializer failing on a cyclic object graph, goes past them to the exception-handling middleware. - **Result filters** run only when an action or action filter produced the result. They are skipped when an authorization or resource filter short-circuits, or when an exception filter handles an exception. Implement `IAlwaysRunResultFilter` (or `IAsyncAlwaysRunResultFilter`) for logic that must touch every result MVC produces. ## Short-circuiting at each stage Every stage can end the request early by producing a result instead of continuing: - an **authorization filter** sets `AuthorizationFilterContext.Result`, typically a 403 or a challenge; - a **resource filter** sets `ResourceExecutingContext.Result`, for example a cached response, and binding never happens; - an **action filter** sets `ActionExecutingContext.Result` and does not call `next`, so the action is skipped but result filters still run; - a **result filter** sets `ResultExecutingContext.Cancel = true` and the result is never executed. Knowing which stage short-circuited tells you which later filters will not see the request, which is the usual root cause when an audit or header filter "randomly" misses responses. ## [Authorize] is not an MVC filter any more With endpoint routing, which `MvcOptions.EnableEndpointRouting` turns on by default, MVC does not convert `[Authorize]` into an `AuthorizeFilter`; the `UseAuthorization` middleware reads the endpoint's metadata and rejects the request before MVC runs. Authorization filters still exist for custom `IAuthorizationFilter` implementations, but a 401 or 403 from `[Authorize]` happens outside the filter pipeline altogether. ## Sync or async Every kind has a synchronous pair of methods (`OnActionExecuting`/`OnActionExecuted`) and an asynchronous one (`OnActionExecutionAsync(context, next)`). Implement one, not both: when a class implements both interfaces, MVC calls only the async method. In the async form you call `await next()` exactly once to run the rest of the pipeline, and you short-circuit by setting `context.Result` and **not** calling `next`. ## Filters versus the other hooks Filters are MVC-specific and know about the action, its arguments and its result. Middleware sees every request, including static files and 404s, but not the action's arguments. Minimal API endpoints have their own endpoint filters, and Razor Pages use page filters instead of action filters. Choosing between them is a separate decision; within MVC, the order above is what interviewers expect you to recite and explain.
- Why can't a resource filter read the action's arguments?Resource filters run before MVC creates the controller and binds arguments, so `ActionArguments` does not exist yet. That is exactly what makes them useful for work that must happen before binding, such as returning a cached response or stopping form binding on large uploads.
- A view throws while rendering. Which filter can see the exception?Not an exception filter: rendering is result execution, which happens outside the exception-filter scope. A result filter's `OnResultExecuted` sees it in `ResultExecutedContext.Exception`, but the response may have started, so the reliable place to handle it is the exception-handling middleware.
- Does a 401 from [Authorize] pass through your IAlwaysRunResultFilter?No. With endpoint routing the authorization middleware rejects the request before MVC's invoker runs, so no MVC filter of any kind executes. Logic that must see those responses belongs in middleware.
- Exception filters catch errors thrown while a view renders or JSON is serialized.
- Action filters run before model binding, so they can change raw request values.
- Filters run for every request, including static files and unmatched URLs.
- Result filters always run, even when an authorization filter short-circuits.
- [Authorize] is applied as an MVC authorization filter in an endpoint-routed app.