Click here to Skip to main content
15,883,870 members
Articles / Web Development / ASP.NET

Understanding Filters in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
8 Sep 2015CPOL6 min read 9.6K   4  
Understanding Filters in ASP.NET MVC

Introduction

Filters are interesting and somewhat unique part of ASP.NET MVC. Filters are designed to inject logic in between MVC request life cycle events. Filters provide developers with powerful ways to inspect, analyze, capture and instrument several things going around within MVC application. Understanding when each of the filters kick in and play the role can greatly enhance the way developers write logic. Plus it gives a very interesting perspective to understand how filters run at multiple points in the request life cycle and have the power to control further execution or prevent request from executing further. As of MVC5, there are 5 types of filters.

image

Authentication Filters

Authentication filters are a new addition from MVC 5. These filters kick in first in the request life cycle and perform the authentication logic.

Authorization Filters

Authorization filters are executed after the Authentication filters successfully executed and authorizes users roles to ensure current user has access to request resource.

Action Filters

Action filters are executed next in the request life cycle and execute any custom logic you may want to perform before and after action execution.

Result Filters

Result filters are executed before and after result execution.

Exception Filters

Finally, the exception filters are executed when there is an exception during processing of request.

The following diagram depicts when each of the filter fires in the MVC request life cycle.

As you can see from the below diagram, as soon as the controller starts execution through Action Invoker, Authentication and authorization filters are the very first filters to be triggered, followed by model binding which maps request and route data to action parameters which is then followed by Action filter execution. OnActionExecuting fires before the action has been executed and OnActionExecuted is fired after the Action method has finished execution. Last comes the Result filters, OnResultExecuting gets fired before executing result, and OnResultExecuted gets fired after the result has been executed. Exception filters are special filters in the sense that they get fired as soon as an exception is thrown and you can write your custom logic to log exception or redirect user to a error page and take appropriate action in this filter.

image

Filters in Action

Like any other life cycle events of MVC, implementing filters in MVC is very easy.

Authentication Filter

Let's start with Authentication Filter, this filter is a recent addition to MVC 5, there is no way you would be able to implement this filter in your older apps. You can leverage this filter for performing authentication related stuff. In the request life cycle, after the URL Routing module has selected the route and controller have been initialized, the first thing that kicks off in the Action method execution is Authentication Filter.

To implement Authentication Filter, you must implement IAuthenticationFilter interface along with deriving from FilterAttribute base class. The key here is IAuthenticationFilter interface that lets you implement two methods, OnAuthentication and OnAuthenticationChallenge. OnAuthentication is primarily used for setting identity principle or any other type of authentication that your application understands. OnAuthenticationChallenge is the special method which gets executed just before the result execution. The reason might be that as a developer, you would want to do some checks here like authorization or redirecting user to a different login page in case of a HttpUnauthorisedResult case. OnAuthenticationChallenge is used to add a “challenge” to the result before it is returned to the user. Here is how you would implement it:

image

Don’t worry about “StoreInSession” method call for now, it's just logging the events in the session, we will see the output at the end of this to understand what it's doing.

Action Filters

Action Filters are the filters that gets executed before and after a method, you can use this filter to implement instrumentation like action performance and other things. To implement Action filter, you need to implement IActionFilter interface and derive from FilterAttribute base class. IActionFilter gives you two methods to implement, OnActionExecuting and OnActionExecuted,. OnActionExecuting gets executed before the Action method execution and OnActionExecuted gets fired after the action method execution.

image

Authorization Filter

Authorization filter has been in use for performing authentication and other stuff prior to Authentication filters. to implement Authorization Filter, you need to implement IAuthorizationFilter interface and derive from FilterAttribute base class. The interface IAuthorizeFilter gives you one method to implement, “OnAuthorization” where you can perform authorization related checks.

image

Result Filter

Result filters are the filters that gets executed before and after executing result to a particular http request. you can leverage these filters to do various checks like instrumentation, or manipulating results before they are sent back to browser, etc. to customize Result filter, implement IResultFilter interface along with deriving from FilterAttribute class.

image

Exception Filter

Exception filters are special filters in the sense that they occur when there is an exception in request execution. You can implement and customize this filter to catch exception as it occurs and probably log it to file system or database and then redirect use to an error page or take any other action that suits your need. To customize this filter, implement IExceptionFilter and derive from FilterAttribute base class.

image

Finally, once you have customized all your filters, you would need to go and tell MVC framework to hook up your filters in the request life cycle. This process is called as registration of filters in MVC life cycle. Just by implementing some interfaces doesn’t lead to automatic discovery of new customized version of filter to take into effect.

Registering filters could be done in two ways, the first one is to put as controller or action attributes, but in that case you would need to remember putting it on all the controllers or actions. Another way of registration is to register at a global level, that way you are assured that it will get executed for all the controllers and actions.

For option #2, go to Global.asax.cs and under Application_Start event, register the customized filters as follows:

image

That’s it. Once you have registered your filters, MVC framework will take care of invoking them throughout the life cycle.

Coming back to output of capturing events and logging details in session.

Refer to the attached source code, the link is available at the top of this blog. In a nutshell, all I have done in the source code is to implement all the filters and add a log entry into the Session to see which ones gets fired and the order of it (just to validate my diagram at the beginning).

The output of the application is as follows, as you can see OnAuthentication is fired first, followed by OnAuthorization, then Action filters (OnActionExecuting and OnActionExecuted), followed by OnAuthenticationChallenge (which I told earlier that it will be fired before executing results), followed by Result filters (OnResultExecuting and OnResultExecuted). You might be wondering why OnResultExecuted is not shown here? That is because OnResultExecuted is fired after sending result back to browser, i.e., we see this page and that concludes our request.

image

Final Thoughts

MVC is a very flexible and robust framework, and Microsoft has written this framework with lot of thinking in mind. Custom filters are a great example of MVC’s features. Use these filters as and when required and leverage one of the best frameworks by Microsoft.

The source code can be found here.

As always, feedback, suggestions or comments are always welcome!

Happy coding!

Filed under: CodeProject

Tagged: Filters in ASP.NET MVC

Image 10 Image 11

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --