Understanding Filters in MVC

Introduction
 
There are situations in which we have an implementation that will be reused in many places that is not confined to a single place or method. This is fulfilled by the Filters in MVC. This is a very good concept introduced in MVC. The implementation that is said above is called cross-cutting concerns. Thus, in simple terms, this adds extra logic to be implemented into the request being processed. Some of the examples of cross-cutting conerns are Authorization & Output Caching. Let's discuss the various types of filters and how to create them and use them.
 
Getting started
 
Let's first see a glimpse at how the filters are used:
  1. namespace WebSecurityDemoTest.Filters  
  2. {  
  3.     public class WebSecurityAuthorize : AuthorizeAttribute  
  4.     {  
  5.         protected bool AuthorizeCore(HttpContextBase httpContext)  
  6.         {  
  7.             if (!httpContext.Request.IsAuthenticated)  
  8.             {  
  9.                 return false;  
  10.             }  
  11.             if (HttpContext.Current.Session["SessionHelper"] == null)  
  12.             {  
  13.                 return false;  
  14.             }  
  15.   
  16.             return true;  
  17.         }  
  18.         protected void HandleUnauthorizedRequest(AuthorizationContext filterContext)  
  19.         {  
  20.             filterContext.Result = new RedirectResult("/");  
  21.             base.HandleUnauthorizedRequest(filterContext);  
  22.         }  
  23.   
  24.     }  
  25. }  
The preceding snippet is an example of an CustomAuthorize attribute. This attribute is a kind of Filter only. Since this is defined here once and is used as an MVC attribute in many places, this needs to be checked at every controller level in every application where athorization is required. Now let's see if this would not have been the case, how explicitly we would have checked at every action level.
  1. namespace WebDemo.Controllers  
  2. {  
  3.     public class DemoController : Controller  
  4.     {  
  5.         //..instances or constructor if any read onlyvariables used  
  6.         public ActionResult Index()  
  7.         {  
  8.             if (!Request.IsAuthenticated)  
  9.             {  
  10.                 FormsAuthenticationn.RedirectToLoginPage();//MVC WebSecurity  
  11.             }  
  12.             //else rest implementation..  
  13.         }  
  14.     }  
  15. }  
In the preceding snippet, as you can see, the Request.IsAuthenticated is checked at each action level, since the authentication needs to be checked before letting the anonymous user access the action. Thus redundancy can be normalized using Filters by just using [Authorize] or [CustomAuthorize] at the controller/action level. Thus we can say Filters are attributes that help in adding an extra check at the routing level, since this needs to be checked during the request processing only. Attributes are special classes derived from the namespace System.Attribute. Basically there are four types of filters that the MVC framework support. They are:

Filter Type Inheritance What this does
Authorization IAuthorizationFilter Runs first during the request processing before any other filters or the action execution
Action IActionFilter Runs before the action execution(Action level)
Result IResultFilter Runs before after the action execution(Action level)
Exception IExceptionFilter Runs only when any action method or any other filter throw exception

Before the invocation of any action method, the framework first looks for any definition of any filter attributes, then moves into the action method execution that in turn gives an extra level of security to the application without writing redundant code. Let's look into each briefly.

Authorization Filter
 
This as the name suggests is required to provide authoization level in the application. The default attribute is [Authorize]. Its constructor also can accept parameters like Roles [Authorize(Roles="Admin")] that is very handy as the roles based application are very common now a days. Authorization filters as specified in the table above runs the first before any filter's execution or even before the action methos execution. The following snippet shows how the Interface from which it extends looks as in:
  1. namespace System.Web.MVC  
  2. {  
  3.     public interface IAuthorizationFilter  
  4.     {  
  5.         void OnAuthorization(AuthorizationContext filterCOntext);  
  6.     }  
  7. }  
The best thing is we can customize the Authorize attribute by extending our custom authorize class from the Authorize attribute class and manipulate our logic there that I have said in the very first snippet. A nice tip here is to keep the Custom Authorize attribute very simple. Built in Authorize attribute also accept the Users parameter like [Authorize(Users="Suraj","Simon","Mike")], that filters the action based on the users access level. The use is also very simple. Either we can use at the controller level or the action level. Just place [CustomAuthorize] before the controller class or the action methods. Action Filter The action filter can be used for any purpose, why any as the interface it extends supports two methods to be invoked. As mentioned in the table, this filter may be executed before the Action execution but not first. Let's look at the interface.
  1. namespace System.Web.MVC  
  2. {  
  3.     public interface IActionFilter  
  4.     {  
  5.         void OnActionExecuting(ActionExecutingContext filterContext);  
  6.         void OnActionExecuted(ActionExecutedContext filterContext);  
  7.     }  
  8. }  
As you can see in the preceding snippet, the interface has two methods to be defined, As the method names suggest, the first one OnActionExecuting tells us that before the action method has been invoked we can use this method, similarly the second one says that once the action method is executed this can be invoked. Now let's see each of them one by one.
filter controller
 
OnActionExecuting Method
 
As has already been said, this method is invoked before the action begins execution. The filterContext of type ActionExecutingContext is ed since the parameter contains the following properties:

Name Description
ActionDescriptor This provides the details of an action method
Result This gives the result for the action method, the filter can be manipulated to cancel the request also

Let's look into the implementation of this method, in a custom action filter attribute:
  1. namespace Filters.WebDemoInfra  
  2. {  
  3.     public CustomActionFilter : FilterAttribute , IActionFilter   
  4.     {  
  5.        public void OnActionExecuting(ActionExecutingContext filterContext)  
  6.        if(filterContext.HttpContext.Request.IsLocal)   
  7.        {  
  8.           filterContext.Result = new HttpNotFoundResult();  
  9.        }  
  10.     }  
  11. }  
Thus when we try and understand what we have written in the snippet above, we find that, before the action is executed, this method is invoked, the method OnActionExecuting returns a not null result. In other words HttpNotFoundResult that will land the user on a 404 not found error page, even if the action has a view defined. This is the power of this filter. Now let's look into it's sister's implementation.
 
OnActionExecuted
 
This method as defined previously, can be invoked to span the execution of the action method being processed based on the request. Let's check using an example that will measure the time taken for the action to complete the full execution.
  1. namespace Filters.WebDemoInfra  
  2. {  
  3.     public class CustomActionFilter : FilterAttribute, IActionFilter  
  4.     {  
  5.         private StopWatch watch; //System.Diagnostics  
  6.         public void OnActionExecuting(ActionExecutingContext filterContext)  
  7.         {  
  8.             timer = Stopwatch.StartNew();  
  9.         }  
  10.   
  11.         public void OnAcionExecuted(ActionExecutedContext filterContext)  
  12.         {  
  13.             timer.Stop();  
  14.             if (filterContext.Exception == null)  
  15.             {  
  16.                 filterContext.HttpContext.Response.Write(string.Format("Total Tme taken: {0}", timer.Elapsed.TotalSeconds));  
  17.             }  
  18.         }  
  19.     }  
  20. }  
The preceding snippet is a very simple sippet to understand. The private variable is of type StopWatch that is an built-in class in the namespace System.Diagnostics. In the executing method, we are initializing the timer and after execution of the action method since the executed method is invoked, the httpContext that contains both the request and response as well, we assign the time elapsed in seconds to the response. Let's look at the properties provided by the OnActionExecuted method.

Name Description
ActionDescriptor This provides the details of an action method
Cancelled If incase the action has been cancelled by any other filter this property returns true
Exception If any filter or any action throws an exception, it is returned by this property
ExceptionHandled If any filter or any action throws an exception and it has been handeled, this property returns true
Result This gives the result for the action method, the filter can be manipulated to cancel the request also

Thus, this was all about the Action filters. Result Filter These are quite similar to the Action Filters. These are the filters that are invoked or operate on the results being produced by the Action Result methods. This implements from the IResultFiler interface that also looks quite similar to the IActionFilter. Let's see how:
  1. namespace System.Web.MVC  
  2. {  
  3.     public interface IResultFilter  
  4.     {  
  5.         void OnResultExecuting(ResultExecutingContext filterContext);  
  6.         void OnResultExecuted(ResultExecutedContext filterContext);  
  7.     }  
  8. }  
OnResultExecuting
 
The OnResultExecuting method is invoked when a result has been returned by the Action method but before the the action is executed fully. This also has the same properties as the OnActionExecuting method as described in the table.
 
OnResultExecuted
 
The OnResultExecuted method is invoked after the action result has been executed. Here also the parameter filterContext contains the same properties as the OnActionExecuted method as described in the table above. The demostration can be the same Timer as described in the Action filter section. The following snippet will show you the built-in Action and Result Filter classes.
  1. public Abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter  
  2. {  
  3.     public virtual void OnActionExecuting(ActionExecutingContext filterContext)  
  4.     {  
  5.     }  
  6.     public virtual void OnActionExecuted(ActionExecutedContext filterContext)  
  7.     {  
  8.     }  
  9.     public virtual void OnResultExecuting(ResultExecutingContext filterContext)  
  10.     {  
  11.     }  
  12.     public virtual void OnResultExecuted(ActionExecutedContext filterContext)  
  13.     {  
  14.     }  
  15. }  
Using Global Filters
 
This is a very nice feature that can be implemented in the MVC application. Global.asax as we all know is the heart of the MVC web application. The Application_Start method is called from here whenever the application starts. We have a FilterConfig.cs file inside our App_start folder, where we can find a static method called RegisterGlobalFilters. In this method we register our custom filter that needs to be invoked throughout the application that is applied to all controllers and actions in the application. Let's see how we register:
  1. namespace Filters  
  2. {  
  3.     public class FilterConfig  
  4.     {  
  5.         public static void RegisterGlobalFilters(GLobalFilterCollection filters)  
  6.         {  
  7.             filters.Add(new HandleErrorAttribute());  
  8.             filters.Add(new CustomAllAttribute());  
  9.         }  
  10.     }  
  11. }  
Thus the second filter added/registered as the global filter is our custom attribute. This custom attribute implementation needs to be thought upon and then written since this would be used throughout the application, so this should also be very simple so that it can be manipulated and maintained at any point of time.
 
Filter Ordering
 
In the MVC framework, the order in which the filter is invoked (if there is more than one at the action), does not matter much. But even if you wish to add ordering based on the business logic we have, then we can use the Order keyword that accepts an int value to set the order of the Filter invokation/execution. Let's use an example and understand.
  1. [ProfileA(Message = "First")]  
  2. [ProfileB(Message = "Second")]  
  3. public ActionResult Index()  
  4. {  
  5.     //Implementation  
  6. }  
In the preceding snippet we have the two custom filters ProfileA and ProfileB that take a message as parameter and print that using the context response write method. Thus, this would write "First" (For OnActionExecuting) "Second" (For OnActionExecuting) "Second" (For OnActionExecuted) "First" (For OnActionExecuted). Thus if we wish to modify the order like the "Second" would come first then the "First", then we need to use Order.
  1. [ProfileA(Message = "First"), Order=2]  
  2. [ProfileB(Message = "Second"), Order=1]  
  3. public ActionResult Index()  
  4. {  
  5.     //Implementation  
  6. }  
Thus, here the output as in the previous will change based on the order specified in the preceding snippet. Thus based on the requirements we can specify as many filters, it may it be built-in or custom and set the order of execution also. This is how flexible the MVC framework is. :)
 
Conclusion
 
Thus here I tried to explain the filters that are being used in MVC framework. Here I have discussed Authorize, Action & Result filters. I will try and explain the Exception Filters in the next section. Thanks for your patience. Corrections and suggestions are humbly accepted. :)
 
References
  • Adam Freeman: Pro ASP.NET MVC

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now