Filters are a unique feature of Asp.Net MVC which are used to inject custom logic before or after the action methods. The filters provide usability to analyse, verify and use data or actions of application in MVC. Knowledge of filters can help you greatly in writing logic before or after execution of MVC request life cycle events. This logic can control the execution or even restrict further execution of events.
Let's understand this with a simple example.
Whenever any request from a user is made, it is processed and the corresponding controller action provides requested view as a response to the user. Suppose, we need some extra processing in between this request- response cycle.
For example, verification of role of the user. In this situation filters are used to insert extra logic in between the request response cycle.
There are 5 types of filters in MVC5.
Filter in Asp.net MVC |
Authentication filters:
Authentication filters are added features in MVC 5. These filters are executed in first place in request life cycle methods. These filter perform the authentication based on the logic.
Authorization filters:
Authorization filters are the second filter types to be executed. This filter executes after authentication filters successfully authorize roles to different users. This filters ensure that the current user is authorized to access the resources or not.
Action filters:
After authorization filters comes the time for execution of action filters. These filters simply execute the piece of logic before and after execution of controller methods.
Result filters:
Result filters are executed before and after result execution.
Exception filters:
As the name denotes, Exception filters are executed if any exception occurs while processing the request.
Diagram below will help you understand the sequence of execution of filters.
Action Method Execution process |
It's clear from the above diagram that as the controller executes, the filters, (Authentication and authorization) are triggered at very first. After this the model binding is done. Out of two IActionFilter interface methods the first one that is, “OnActionExecuting” is fired before execution of the action and the second one “OnActionExecuted“ is fired after the action execution.
At the last, there are result filters which are executed. Again, this filter implements two interface methods from IResultFilter interface. At first “OnResultExecuting” which is fired before the execution of the result, while “OnResultExecuted“ is fired after is fired after the action execution.
Exception filter is fired in those cases when exception is thrown. Here we can write our custom logic either to record exceptions as log or redirect to any error page.
Filters in Action:
Like any other life cycle events of MVC, implementing filters in MVC is very easy.
Authentication Filter:
The very first one in the queue is the Authentication Filter, which is added recently in MVC5. This filter gives us maximum benefits and can be used for all authentication related exercise. As we know,after URL routing, controller gets initialized and authentication filters comes in picture.
This filter implements IAuthenticationFilter interface as well as FilterAttribute base class. IAuthenticationFilter interface has got two methods, OnAuthentication and OnAuthenticationChallenge. OnAuthentication is mostly used for any type of authentication that is understood by our application including setting of identity Principle.
Now comes OnAuthenticationChallenge which gets executed before result execution. The result might require some checks to authorize users and identify unauthorise users in case of a HttpUnauthorisedResult case. Here OnAuthenticationChallenge is used to perform this check by adding some “challenge” to the result before it is sent to users.
How to implement??
Code:
using System.Web.Mvc.Filters; using FilterAttribute = System.Web.Mvc.FilterAttribute; namespace MvcFilters.CustomFilters { public class AuthenticationFilter : FilterAttribute, IAuthenticationFilter { public void OnAuthentication(AuthenticationContext filterContext) { Utils.SessionManager.StoreInSession(filterContext, "OnAuthentication"); } public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) { Utils.SessionManager.StoreInSession(filterContext, "OnAuthenticationChallenge"); } } }
As you must be wondering about the use of “StoreInSession” method call. So let’s clear it that these methods are just used to log all events in the session so that we could see the result at last.
Action Filters:
Action Filters require implementation of IActionFilter interface and FilterAttribute base class. The IActionFilter interface executes two methods namely OnActionExecuting which is executed before action method execution and OnActionExecuted which is executed after the action method execution.
Code:
using System.Web.Mvc; using FilterAttribute = System.Web.Mvc.FilterAttribute; using IActionFilter = System.Web.Mvc.IActionFilter; namespace MvcFilters.CustomFilters { public class ActionFilter : FilterAttribute, IActionFilter { public void OnActionExecuted(ActionExecutedContext filterContext) { Utils.SessionManager.StoreInSession(filterContext, "OnActionExecuted"); } public void OnActionExecuting(ActionExecutingContext filterContext) { Utils.SessionManager.StoreInSession(filterContext, "OnActionExecuting"); } } }
Authorization Filter:
Authorization filter performs all necessary duties required for authentication process has been in use for performing authentication before the authentication filters. It implements 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.
Code:
using System.Web.Mvc; using FilterAttribute = System.Web.Mvc.FilterAttribute; using IAuthorizationFilter = System.Web.Mvc.IAuthorizationFilter; namespace MvcFilters.CustomFilters { public class AuthorizationFilter : FilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { Utils.SessionManager.StoreInSession(filterContext, "OnAuthorization"); } } }
Result Filter:
Result filter are the filters that gets executed before and after executing result to a particular http request. These filters perform checks and manipulate result before it is sent to the browser. The result filter implements IResultFilter interface and derives from FilterAttribute class.
Code:
using System.Web.Mvc; using FilterAttribute = System.Web.Mvc.FilterAttribute; using IResultFilter = System.Web.Mvc.IResultFilter; namespace MvcFilters.CustomFilters { public class ResultFilter : FilterAttribute, IResultFilter { public void OnResultExecuted(ResultExecutedContext filterContext) { Utils.SessionManager.StoreInSession(filterContext, "OnResultExecuted"); } public void OnResultExecuting(ResultExecutingContext filterContext) { Utils.SessionManager.StoreInSession(filterContext, "OnResultExecuting"); } } }
Exception Filter:
Exception filters are those filters which occur in case of exception in request execution. It can be customized as per the developer’s requirement to either create a log or send user to a different error page. This filter implement IExceptionFilter and derive from FilterAttribute base class.
Code:
using System.Web.Mvc; using FilterAttribute = System.Web.Mvc.FilterAttribute; using IExceptionFilter = System.Web.Mvc.IExceptionFilter; namespace MvcFilters.CustomFilters { public class ExceptionFilter : FilterAttribute, IExceptionFilter { public void OnException(ExceptionContext filterContext) { Utils.SessionManager.StoreInSession(filterContext, "OnException"); } } }
Finally, when customization of all filters is done its required to inform MVC to use them and this is done by registering filters. You must be wondering here that you have already used interfaces to implement filters but let me tell you it is not enough.
Registration of filters is done in following ways-
- We can put them on controller or action methods as attributes.
- We can also register them globally. Here it is not needed to put filters specifically on action or controller methods.
using MvcFilters.CustomFilters; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace MvcFilters { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalFilters.Filters.Add(new AuthenticationFilter()); GlobalFilters.Filters.Add(new AuthorizationFilter()); GlobalFilters.Filters.Add(new ActionFilter()); GlobalFilters.Filters.Add(new ResultFilter()); GlobalFilters.Filters.Add(new ExceptionFilter()); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
In the given source code we have implemented all filters and created a log in the session. That is why we are able to see the execution order of all filters.
The output clearly shows the execution order of the filters in application. We can see that the first filter executed is OnAuthentication, after that OnAuthorization, then ActionFitlers (OnActionExecuting and OnActionExecuted). This is followed by OnAuthenticationChallenge. Now, comes the number of ResultFilters. We cannot see OnResultExecuted as it is fired after result is sent back to the browser.
Filters Execution List |
So, Guys this is all about Filters in Asp.Net MVC.
I Hope in this post I have covered all the points about filters which will be helpful to understand the concept of Filters in Asp.Net MVC.
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
Nice post! I really enjoy this blog
ReplyDeleteDot Net Online Course Hyderabad
MMORPG
ReplyDeleteınstagram takipci satin al
Tiktok Jeton Hilesi
tiktok jeton hilesi
antalya saç ekimi
referans kimliği nedir
İnstagram Takipçi Satın Al
Takipci satin al
Mt2 Pvp Serverler
Smm Panel
ReplyDeletesmm panel
iş ilanları
instagram takipçi satın al
hirdavatciburada.com
beyazesyateknikservisi.com.tr
SERVİS
tiktok jeton hilesi
Good content. You write beautiful things.
ReplyDeletehacklink
sportsbet
mrbahis
korsan taksi
hacklink
vbet
mrbahis
taksi
vbet
başakşehir
ReplyDeletebayrampaşa
beşiktaş
beykoz
beylikdüzü
GG3İ
mecidiyeköy
ReplyDeletesakarya
istanbul
kayseri
ordu
XMUVDX