skip to content

Action & Result Filters

The MVC filter pipeline: authorization, resource, action, exception and result filters, their scopes and Order, short-circuiting, and DI via ServiceFilter and TypeFilter. Asked as which runs when.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

5

In ASP.NET Core MVC, which filter kinds exist and in what order do they run around a controller action?

level: middleimportance: must knowfreq 72%

answer

  1. filters run after action selection
  2. authorization, resource, action, exception, result
  3. resource filters run before model binding
  4. exception filters skip result execution
  5. IAlwaysRunResultFilter

basics

~20 s

MVC 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 s

Filters 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 lines
csharp
public 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

for a junior

Name the five filter kinds and recall that authorization runs first and result filters run around the result.

for a middle

Recite the full order including model binding, explain what each kind can see, and how short-circuiting changes what runs.

for a senior

Place logic correctly: rendering and serialization errors escape exception filters, middleware rejections skip all filters, always-run result filters cover short-circuits.

for a principal

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.
open as a page

In ASP.NET Core MVC, how do you write an action filter that records who called each payroll admin action and how long it took?

level: juniorimportance: should knowfreq 58%

basics

~20 s

Implement IAsyncActionFilter: record the user and start a Stopwatch, await next() to run the action, then read ActionExecutedContext for the result or exception and write the audit entry. Register it globally with Filters.Add<T>() or per controller with [ServiceFilter].

open as a page

In an ASP.NET Core MVC payroll back office, how would an exception filter translate domain exceptions into HTTP responses, and what can it not catch?

level: middleimportance: should knowfreq 50%

basics

~10 s

Implement IExceptionFilter, check context.Exception for a domain type such as PayrollPeriodClosedException, set context.Result to a 409 ProblemDetails and ExceptionHandled = true. It cannot catch exceptions from resource filters, result filters or result execution.

open as a page

In ASP.NET Core MVC, when do you use ServiceFilter, TypeFilter or a custom IFilterFactory to give a filter constructor dependencies, and what can IsReusable break?

level: seniorimportance: should knowfreq 42%

basics

~10 s

[ServiceFilter] resolves a DI-registered filter, [TypeFilter] builds an unregistered one with ActivatorUtilities and extra Arguments, and a custom IFilterFactory gives an attribute both parameters and services. IsReusable = true caches instances, capturing scoped dependencies.

open as a page

In ASP.NET Core MVC, how do filter scope and the Order property decide which filter runs first, and when does a result filter not run at all?

level: seniorimportance: nice to knowfreq 35%

basics

~20 s

MVC sorts filters by Order (default 0) and uses scope only to break ties: global, then controller, then action. Lower Order wraps higher. Ordinary result filters skip authorization or resource short-circuits and handled exceptions; IAlwaysRunResultFilter does not.

open as a page