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

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).


Well, I can't really understand what exactly do you find as a bizarreness here.

Authorization, Action, Response and Exception filters are 4 interfaces you can implement to run the filter logic, IAuthorizationFilter, IActionFilter, IResultFilter and IExceptionFilter interfaces respectively.

After that, the business rules comes out to the lights. For example, you have to check the access rights for some user action. You have not only implement the authorization filter, but create a logic for checking rules like:

  • If user didn't finish registration, you have to remind him about this. This rule should be run at First, no matter what user does on your site.
  • If user hasn't been approved, he can't view site contents, and should gain a validation message. So it is a Global scoped rule, and it should be run before any other checks for user rights.
  • If user has no access for some department, he can't view some content on site regarding that department, but not all - so we let the Controller choose, what should be displayed to user.
  • If user isn't a manager, he can't edit or delete some content. So, this is a concrete Action which is being filtered.
  • We can fire up some logger after task is being processed, so we have to wait until the work is done, and run filter at Last.

I see here a very simple model for the filter ordering, and I can provide a sample for each pair or filter type/filter scope.

Update:

some sample code for a Filter's ordering:

public class ControllerInstanceFilterProvider : IFilterProvider {
    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) {
        if (controllerContext.Controller != null) {
            // Use FilterScope.First and Order of Int32.MinValue to ensure controller instance methods always run first
            yield return new Filter(controllerContext.Controller, FilterScope.First, Int32.MinValue);
        }
    }
}