Raj Aththanayake's Blog Raj Aththanayake's Blog | May 2011

MVC 3 Filter Ordering

14. May 2011

MVC 3 has introduced couple of new approaches related to the run order of filters. In this article, we will look at the order of filters execution.

image

There are different types of filters in MVC. Depending on the type of the Filter, and the scope of the Filter, the order of the execution also changes.

You may already aware that there are different types of filters within MVC framework. They are listed below.

1. Authorization filters

2. Action filters

3. Response/Result filters

4. Exception filters

The above list is ordered as exactly the order they executes within MVC framework. The Authorization filters always run first, and the Exception filters run at the end.

Specifying the Order property for Filters

Within each filter, you may specify the Order property. (All filters are derived from the abstract class FilterAttribute, and this class has an Order property). This property will ensure the filter runs in a specific Order. For an example, let’s say we have 2 Authorization filters, AuthorizationFilterA and AuthorizationFilterB and they are implemented as below.

   1: public class AuthorizationFilterA : AuthorizeAttribute
   2: {
   3:     public override void OnAuthorization(AuthorizationContext filterContext)
   4:     {
   5:         Debug.WriteLine("OnAuthorization : AuthorizationFilterA");   
   6:     }
   7: }
   8:  
   9:  
  10: public class AuthorizationFilterB : AuthorizeAttribute
  11: {
  12:     public override void OnAuthorization(AuthorizationContext filterContext)
  13:     {
  14:         Debug.WriteLine("OnAuthorization : AuthorizationFilterB");
  15:     }
  16: }

Now, if I want these two filters to run in a specific order - AuthorizationFilterB to run first, and AuthorizationFilterA to run second, I can simply specify the execution order as below.

   1: [AuthorizationFilterA(Order=2)]
   2: [AuthorizationFilterB(Order=1)]
   3: public ActionResult Index()
   4: {          
   5:     return View();
   6: }

When you run the code, the Output window should display that AuthorizationFilterB runs first, AuthorizationFilterA runs second.

OnAuthorization : AuthorizationFilterB

OnAuthorization : AuthorizationFilterA

 

Filter Scope

Within each filter type, you can define a scope. For an example, I could scope all my Authorization Filters to run within the Controller Scope, and all Action Filters to run in Global scope (Every Action within the MVC application).

FilterScope.Global is a new scope which was introduced in MVC 3. The existing scopes are First, Controller, Action, and Last. The complete enumeration is defined as below.

   1: namespace System.Web.Mvc {
   2:     public enum FilterScope {
   3:         First = 0,
   4:         Global = 10,
   5:         Controller = 20,
   6:         Action = 30,
   7:         Last = 100,
   8:     }
   9: }

By default, the filters with the lowest scope runs first. For an example, scope Global (10) executes first and scope Controller (20) executes second.

 

Filter Scope with explicit Ordering

Below example shows, how explicit filter ordering (using Order property) and scope of the filters determine their correct run order.

Let’s add the scope to our existing Authorization Filters – AuthorisationFilterA and AuthorisationFilterB. Please note that we haven’t changed the usage of Order property.

AuthorizationFilterA(Order 2) has the scope Global.

AuthorizationFilterB(Order 1) has the scope Action.

   1: public class AuthorizationFilterA : AuthorizeAttribute
   2: {
   3:     public override void OnAuthorization(AuthorizationContext filterContext)
   4:     {
   5:         Debug.WriteLine("OnAuthorization : AuthorizationFilterA (Order: 2) in scope : Global");   
   6:     }
   7: }
   8:  
   9: public class AuthorizationFilterB : AuthorizeAttribute
  10: {
  11:     public override void OnAuthorization(AuthorizationContext filterContext)
  12:     {
  13:         Debug.WriteLine("OnAuthorization : AuthorizationFilterB (Order: 1) in scope : Action");   
  14:     }
  15: }
  16:  
  17:     
  18: [AuthorizationFilterB(Order = 1)]
  19: public ActionResult Index()
  20: {           
  21:     return View();
  22: }
  23:  
  24: GobalFilters.Filters.Add(new AuthorizationFilterA() { Order = 2});

According to the above Filter Scope enumeration, if we were to specify only the scope but not the Order property, then we would expect AuthorizationFilterA (in Global scope) to run first, and AuthorizationFilterB (in Action scope) to run second. Since we are explicitly specifying the Order property for both filters, AuthorizationFilterB (in Action scope – Order 1) runs first and AuthorizationFilterA (in Global scope – Order 2) runs second.

Output:

OnAuthorization : AuthorizationFilterB (Order: 1) in scope : Action

OnAuthorization : AuthorizationFilterA (Order: 2) in scope : Global

Now let’s add another Authorization filter (AuthorizationFilterC) to Global scope. Also note that we have not specified the Order property.

   1: public class AuthorizationFilterC : AuthorizeAttribute
   2:     {
   3:         public override void OnAuthorization(AuthorizationContext filterContext)
   4:         {
   5:             Debug.WriteLine("OnAuthorization : AuthorizationFilterC (no Order defined) in scope : Global");
   6:         }
   7:     }
   8:  
   9: GlobalFilters.Filters.Add(new AuthorizationFilterC());

After running all three filters, you can see the output as below.

 

Output

OnAuthorization : AuthorizationFilterC (no Order defined) in scope : Global

OnAuthorization : AuthorizationFilterB (Order: 1) in scope : Action

OnAuthorization : AuthorizationFilterA (Order: 2) in scope : Global

For same Filter type, the filters without the explicit ordering (i.e AuthorizationFilterC) take precedence over the filters with explicit ordering (AuthorizationFilterB, AuthorizationFilterA).

 

Now let’s remove the Order property from both AuthorizationFilterB and AuthorizationFilterA

   1: [AuthorizationFilterB]
   2: public ActionResult Index()
   3: { 
   4:     return View();
   5: }
   6:  
   7: GlobalFilters.Filters.Add(new AuthorizationFilterA());

 

Output:

OnAuthorization : AuthorizationFilterA (no order defined) in scope : Global

OnAuthorization : AuthorizationFilterC (no order defined) in scope : Global

OnAuthorization : AuthorizationFilterB (no order defined) in scope : Action

As we would expect, the filters with scope Global (AuthorizationFilterA and AuthorizationFilterC) run first and second in order, the scope Action filter (AuthorizationFilterC) runs at the end. 2 Global filters (AuthorizationFilterA and AuthorizationFilterC) run order relies on the order which they were added to the Global Filter collection. In this example AuthorizationFilterA which was added prior to AuthorizationFilterC , runs first.

For the same filters, when determine the run order, first it sorts them by their order (lowest numbers first), and then by their scope (also lowest numbers first).

 

 

Controller as a Filter

In MVC the Controller itself is also a Filter. Controller implements all filters, so Controller can subscribe to all filter events.

   1: public abstract class Controller : ControllerBase, 
   2: IActionFilter, IAuthorizationFilter, IDisposable, 
   3: IExceptionFilter, IResultFilter

MVC framework ensures, the Controller always runs first, before any other filters get executed. It has been accomplished by specifying the scope as the First and the order property as Int32.MinValue. By default, an MVC filter has the value for the Order -1. Therefore Int32.MinValue along with the Scope First together ensures the Controller always runs first.

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

Forward Filter Order and Reverse Filter Order

So far we have discussed the order of filters which get executed based on the explicit ordering (using Order property) and the scope which they can be belong to. However, MVC filters run order, do not only rely only by these two factors. Sometimes filters run in forward order and sometimes filters run in reverse order. Let’s see the below example.

Let’s say I have three Action filters (ActionFilter1, ActionFilter2, ActionFilter3), one Authorization filter (AuthorizationFilter) and two Exception filters (HandleErrorA, HandleErrorB). They are implemented as below.

   1: public class ActionFilter1 : ActionFilterAttribute
   2: {
   3:     public override void OnActionExecuting(ActionExecutingContext filterContext)
   4:     {
   5:         Debug.WriteLine("Forward Order - OnActionExecuting : ActionFilter1 (Scope Global)");
   6:     }
   7:  
   8:     public override void OnActionExecuted(ActionExecutedContext filterContext)
   9:     {
  10:         Debug.WriteLine("Reverse Order - OnActionExecuted : ActionFilter1 (Scope Global)");
  11:     }
  12:  
  13:     public override void OnResultExecuting(ResultExecutingContext filterContext)
  14:     {
  15:         Debug.WriteLine("Forward Order - OnResultExecuting : ActionFilter1 (Scope Global)");
  16:     }
  17:  
  18:     public override void OnResultExecuted(ResultExecutedContext filterContext)
  19:     {
  20:         Debug.WriteLine("Reverse Order - OnResultExecuted : ActionFilter1 (Scope Global)");
  21:     }
  22: }
  23:  
  24:  
  25: public class ActionFilter2 : ActionFilterAttribute
  26: {
  27:     public override void OnActionExecuting(ActionExecutingContext filterContext)
  28:     {
  29:         Debug.WriteLine("Forward Order - OnActionExecuting : ActionFilter2 (Scope Controller)");
  30:     }
  31:  
  32:     public override void OnActionExecuted(ActionExecutedContext filterContext)
  33:     {
  34:         Debug.WriteLine("Reverse Order - OnActionExecuted : ActionFilter2 (Scope Controller)");
  35:     }
  36:  
  37:     public override void OnResultExecuting(ResultExecutingContext filterContext)
  38:     {
  39:         Debug.WriteLine("Forward Order - OnResultExecuting : ActionFilter2 (Scope Controller)");
  40:     }
  41:  
  42:     public override void OnResultExecuted(ResultExecutedContext filterContext)
  43:     {
  44:         Debug.WriteLine("Reverse Order - OnResultExecuted : ActionFilter2 (Scope Controller)");
  45:     }
  46: }
  47:  
  48: public class ActionFilter3 : ActionFilterAttribute
  49: {
  50:     public override void OnActionExecuting(ActionExecutingContext filterContext)
  51:     {
  52:         Debug.WriteLine("Forward Order - OnActionExecuting : ActionFilter3 (Scope Action)");
  53:     }
  54:  
  55:     public override void OnActionExecuted(ActionExecutedContext filterContext)
  56:     {
  57:         Debug.WriteLine("Reverse Order - OnActionExecuted : ActionFilter3 (Scope Action)");
  58:     }
  59:  
  60:     public override void OnResultExecuting(ResultExecutingContext filterContext)
  61:     {
  62:         Debug.WriteLine("Forward Order - OnResultExecuting : ActionFilter3 (Scope Action)");
  63:     }
  64:  
  65:     public override void OnResultExecuted(ResultExecutedContext filterContext)
  66:     {
  67:         Debug.WriteLine("Reverse Order - OnResultExecuted : ActionFilter3 (Scope Action)");
  68:     }
  69: }
  70:  
  71:  
  72: public class AuthorizationFilter : AuthorizeAttribute
  73: {
  74:     public override void OnAuthorization(AuthorizationContext filterContext)
  75:     {
  76:         Debug.WriteLine("Forward Order - OnAuthorization : AuthorizationFilter (Scope Controller)");
  77:     }
  78: }
  79:  
  80:  
  81: public class HandleErrorA : HandleErrorAttribute
  82: {
  83:     public override void OnException(ExceptionContext filterContext)
  84:     {
  85:         Debug.WriteLine("Reverse Order - OnException : HandleErrorA (Scope Action)");
  86:     }
  87: }
  88:  
  89: public class HandleErrorB : HandleErrorAttribute
  90: {
  91:     public override void OnException(ExceptionContext filterContext)
  92:     {
  93:         Debug.WriteLine("Reverse Order - OnException : HandleErrorB (Scope Action)");
  94:     }
  95: }

We will register the above filters as below…

ActionFilter1 has the scope Global, ActionFIlter2 has the scope Controller, ActionFIlter3 has the Scope Action, AuthorizationFilter has the scope Controller, HandleErrorA has the scope Global, and HandleErrorB has the scope Action.

At the beginning of this article I mentioned that the run order of different types of filters. First Authorization filters, then Action Filters, followed by Result filters and at the end the Exception filters. This is true, however within each type of filters, some executes in reverse order and some executes in forward order.

The best way to explain is to examine the generated output.

Forward Order - OnAuthorization : AuthorizationFilter (Scope Controller)

Forward Order - OnActionExecuting : ActionFilter1 (Scope Global)

Forward Order - OnActionExecuting : ActionFilter2 (Scope Controller)

Forward Order - OnActionExecuting : ActionFilter3 (Scope Action)

Home Controller, Index Action

Reverse Order - OnActionExecuted : ActionFilter3 (Scope Action)

Reverse Order - OnActionExecuted : ActionFilter2 (Scope Controller)

Reverse Order - OnActionExecuted : ActionFilter1 (Scope Global)

Forward Order - OnResultExecuting : ActionFilter1 (Scope Global)

Forward Order - OnResultExecuting : ActionFilter2 (Scope Controller)

Forward Order - OnResultExecuting : ActionFilter3 (Scope Action)

Reverse Order - OnResultExecuted : ActionFilter3 (Scope Action)

Reverse Order - OnResultExecuted : ActionFilter2 (Scope Controller)

Reverse Order - OnResultExecuted : ActionFilter1 (Scope Global)

Reverse Order - OnException : HandleErrorB (Scope Action)

Reverse Order - OnException : HandleErrorA (Scope Global)

 

  • There is only one Authorization Filter in Controller scope and it runs first as expected.

 

  • The Action Filters run at second. Notice that OnActionExecuting event runs in an order where the order of filter execution is determined by their scope (lowest number first in the enumeration). As you see, Action Filters OnActionExecuting event runs in a forward order.

 

  • Home Controller’s Index Action executes.

 

  • Action Filters do not always run in forward order. As you see during OnActionExecuted event, they run in a reverse order.

 

  • Very similar to OnActionExecuted event, OnResultExecuted event runs in reverse order.

 

  • Error Handler filters run at last. For each Error Handler filter, OnException event runs in  reverse order. Prior to MVC 3, ErrorHandler’s OnException event ran in forward order. This approach makes MVC exception filters more aligned with .NET exception handlers.

 

 

Summary

There are multiple factors involved when deciding the run order of MVC filters. This includes the explicit ordering, the scope they belong to, and the type of the filter. Controller itself is a filter and always run first. By design, MVC executes certain filters in specific order. Some are run in forward order and some are run in reverse order.

ASP.NET / ASP.NET MVC

A tip on type Inference in Generic Methods

5. May 2011

As you may already know C# support type interfaces for generic methods. I have seen many developers write code like below for both extension methods and generic methods.

   1: public static bool IsGreaterThan<T>(T x, T y) where T : IComparable<T>
   2:         {
   3:             if (x.CompareTo(y) > 0)
   4:             {
   5:                 return true;
   6:             }
   7:  
   8:             return false;
   9:         }

Extension method:

   1: public static bool IsGreaterThanExt<T>(this T x, T y) where T : IComparable<T>
   2:         {
   3:             if (x.CompareTo(y) > 0)
   4:             {
   5:                 return true;
   6:             }
   7:  
   8:             return false;
   9:         }

The Usage:

   1: Console.WriteLine(IsGreaterThan<int>(4, 3));
   2:  
   3: Console.WriteLine(4.IsGreaterThanExt<int>(3));
   4:  

The above <int> is redundant. The reason is that the type is automatically inferred by the C# compiler.

Now you can simply call the methods without the type <T>

 

   1: Console.WriteLine(IsGreaterThan(4, 3));
   2:  
   3: Console.WriteLine(4.IsGreaterThanExt(3))

 

C#