Search code examples
c#asp.net-mvcaction-filter

What is the Filter Scope for and why the weird names?


According to this documentation for ASP.NET Filters filters run in the following order:

  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters

The within each filter type there is a filter Order which specifies the run order.

Makes sense so far... but then it gets bizarre.

There is a further method of ordering within each filter type and order which is represented as an enumeration of the following values:

public enum FilterScope
{
    First = 0,
    Global = 10,
    Controller = 20,
    Action = 30,
    Last = 100,
}

What bearing does Global, Controller and Action have within the run order for an action filter?

For example:

If I have two Action Filters, both with a run order of 1 and FilterScope of Controller and Action respectively.

Other than ordering one in front of the other, what bearing does Controller and Action have on anything?

Further Bizarreness

According to this the FilterScope provides third level ordering for filters. How is Controller, Global, or Action an order for a filter that is in no way restricted for use on just a Controller, Action and not necessarily applied globally? It isn't descriptive of an order.

Also, if it does provide third level filtering, why is it restricted to just the 5 options?


Solution

  • Filter objects, the objects that actually have a Scope property, are constructed based on usage - when you add a filter to the global application filters, a Filter object is constructed with a Scope of Global. Similarly, when filter attributes are collected from the controller and the action, Filter objects are constructed using scopes of Controller and Action, respectively.

    I'm not entirely sure how a Filter with a Scope of First or Last actually gets created.

    These rules are specified to say how tie-breaking will be applied should you have a filter declared at, say, the global level and at the action level using the same Order value - which is more of a concern than filters declared at the same level where you're expected to manually ensure that each filter uses a unique Order (if you care about ordering).