skip to content

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%

answer

  1. Global 10, Controller 20, Action 30
  2. Order first, scope breaks ties
  3. lower Order: before code first, after code last
  4. controller's own hooks at int.MinValue
  5. IAlwaysRunResultFilter after short-circuits

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.

solid answer

~40 s

Every filter gets a `FilterDescriptor` with a scope (`FilterScope.Global` 10, `Controller` 20, `Action` 30) and an `Order` from `IOrderedFilter`, 0 by default. The comparer sorts by `Order` and falls back to scope only when the orders are equal, so global filters wrap controller filters, which wrap action filters, unless someone sets `Order`. Lower `Order` means outer: its before code runs first and its after code last. A controller deriving from `Controller` is itself a filter at controller scope with `Order = int.MinValue`, so its `OnActionExecuting` normally runs before every other action filter. Ordinary result filters are skipped when an authorization or resource filter short-circuits and when an exception filter handles an exception. `IAlwaysRunResultFilter` runs in all those cases, which makes it the place for a header that every MVC response must carry.

code

csharp · 13 lines
csharp
public sealed class NoStoreHeaderFilter : IAlwaysRunResultFilter
{
    public void OnResultExecuting(ResultExecutingContext context) =>
        context.HttpContext.Response.Headers.CacheControl = "no-store";

    public void OnResultExecuted(ResultExecutedContext context) { }
}

builder.Services.AddControllers(o =>
{
    o.Filters.Add<NoStoreHeaderFilter>();          // also on short-circuited results
    o.Filters.Add<AuditFilter>(order: -3000);       // outside the automatic 400 (-2000)
});

go deeper

for a junior

Recall that filters can be global, on the controller or on the action, and that global ones run first by default.

for a middle

Explain the Order-then-scope sort, the nesting of before and after code, and which short-circuits skip ordinary result filters.

for a senior

Order filters deliberately around framework filters such as the -2000 automatic 400, and use always-run result filters for headers that must survive short-circuits.

for a principal

Publish an ordering convention for platform-wide filters so teams adding their own know which numbers are reserved and why.

## Scope A filter can be attached in three places, and MVC records where it came from as a **scope**, an integer on `FilterScope`: - `FilterScope.Global = 10`: added through `MvcOptions.Filters` in `AddControllers(o => ...)`. - `FilterScope.Controller = 20`: an attribute on the controller class. - `FilterScope.Action = 30`: an attribute on the action method. (`FilterScope.First` is 0 and `FilterScope.Last` is 100, bounds for custom providers.) ## Order A filter implementing `IOrderedFilter` exposes `int Order`. The attribute base classes (`ActionFilterAttribute`, `ResultFilterAttribute`, `ExceptionFilterAttribute`) and `ServiceFilterAttribute`/`TypeFilterAttribute` all implement it with a default of 0; `Filters.Add<T>(order)` sets it for global filters. ## How they combine The sort comes from `FilterDescriptorOrderComparer`: 1. Compare `Order`; the lower value sorts first. 2. Only if the orders are equal, compare scope; the lower scope sorts first. The sorted list is then **nested**: the first filter is the outermost wrapper. For action filters that gives: | Step | Filter (all at Order 0) | Method | |---|---|---| | 1 | global audit filter | `OnActionExecuting` | | 2 | controller `[PayrollLock]` | `OnActionExecuting` | | 3 | action `[RequireApprover]` | `OnActionExecuting` | | 4 | — | action runs | | 5 | action `[RequireApprover]` | `OnActionExecuted` | | 6 | controller `[PayrollLock]` | `OnActionExecuted` | | 7 | global audit filter | `OnActionExecuted` | Give the action-level `[RequireApprover]` an `Order = -1` and it becomes the outermost filter, even though it was declared on the method. ## Special orders worth knowing - A controller deriving from `Controller` implements `IActionFilter` and `IAsyncActionFilter`; MVC adds it as a `ControllerActionFilter` at controller scope with `Order = int.MinValue`, so its `OnActionExecuting` runs before any other action filter unless a global filter also uses `int.MinValue` (same order, lower scope). - `[ApiController]`'s `ModelStateInvalidFilter` uses `Order = -2000`, so an invalid model returns its 400 before action filters at the default order run. A filter that must see invalid requests needs an `Order` below -2000. - Order only compares filters of the **same kind**. An action filter with `Order = -5000` still runs after every resource filter; kinds are stages, and `Order` sorts within a stage. ## Reserving numbers on a team Once several global filters exist, ad-hoc `Order` values collide. A payroll platform might reserve bands and document them next to the registration code: 1. below -2000: filters that must see every request, including ones the automatic 400 rejects (audit, request tracing); 2. -2000: the framework's `ModelStateInvalidFilter`; 3. -1000 to -1: platform policies that need valid models (payroll-period locks, approver checks); 4. 0: everything a feature team adds without thinking about order; 5. positive values: filters that must sit closest to the action, such as argument normalisation. A convention like this turns ordering bugs into code-review questions instead of production surprises. ## When result filters do not run Ordinary result filters (`IResultFilter`, `IAsyncResultFilter`, `ResultFilterAttribute`) run only when an action or an action filter produced the result. They are skipped when: - an authorization filter sets `context.Result`; - a resource filter short-circuits; - an exception filter handles an exception and supplies the result. `IAlwaysRunResultFilter` and `IAsyncAlwaysRunResultFilter` run for all of those results too. Use them for a correlation header, a `Cache-Control: no-store` on payroll data, or a uniform error shape. Two limits remain: they do not run for anything rejected **before** MVC (for example `UseAuthorization` answering 401 for `[Authorize]` under endpoint routing), and they cannot change a response whose headers have already been sent. ## Debugging the order When a filter runs earlier or later than expected, let MVC tell you. With the `Microsoft.AspNetCore.Mvc` log category at Debug, the action invoker logs "Execution plan of {FilterType} filters (in the following order): {Filters}" for each kind before running the action, and at Trace level adds "Before executing" and "After executing" lines for each filter method. Read the plan, compare it with the `Order` values you expected, and remember that factory-created filters are listed by the filter they produced. A result filter can also short-circuit the result itself: setting `ResultExecutingContext.Cancel = true` skips the result and later result filters, and `ResultExecutedContext.Canceled` tells the outer filters it happened.

  • Can an action filter with a very low Order run before a resource filter?
    No. `Order` sorts filters within one stage. All authorization filters run before resource filters, which run before model binding and action filters, regardless of the numbers; only filters of the same kind compete on `Order` and scope.
  • Why might a header added by an IAlwaysRunResultFilter still be missing from a 401?
    Under endpoint routing, `[Authorize]` is enforced by the authorization middleware before MVC's invoker runs, so no MVC filter executes. Headers every response needs belong in middleware, for example with `Response.OnStarting`.

  • Scope always wins: an action-level filter can never wrap a global one.
  • A lower Order makes a filter run its after code first as well.
  • An action filter with Order -5000 runs before the resource filters.
  • Result filters run for every result, including ones set by authorization filters.
  • IAlwaysRunResultFilter also runs for 401s produced by UseAuthorization.