• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Sunday, August 20, 2017

Filters in ASP.Net MVC

 Abhishek Tomer     August 20, 2017     .Net, Asp.Net MVC, Filters     6 comments   

Hi friends! Today we are going to discuss about using a very important feature of MVC i.e.“Filters“.

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
Filter in Asp.net MVC
Now, Let's discuss each one of them in details.

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 in MVC
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. 
This is done by registering filters in Application_Start event in Global.asax file. See the example below.

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
Filters Execution List
Summary:
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 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

6 comments:

  1. rmouniakSeptember 4, 2018 at 5:19 PM

    Nice post! I really enjoy this blog
    Dot Net Online Course Hyderabad

    ReplyDelete
    Replies
      Reply
  2. AnonymousApril 30, 2022 at 1:02 PM

    MMORPG
    ı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

    ReplyDelete
    Replies
      Reply
  3. AnonymousMay 26, 2022 at 5:22 AM

    Smm Panel
    smm panel
    iş ilanları
    instagram takipçi satın al
    hirdavatciburada.com
    beyazesyateknikservisi.com.tr
    SERVİS
    tiktok jeton hilesi

    ReplyDelete
    Replies
      Reply
  4. sportsbetDecember 23, 2022 at 6:12 AM

    Good content. You write beautiful things.
    hacklink
    sportsbet
    mrbahis
    korsan taksi
    hacklink
    vbet
    mrbahis
    taksi
    vbet

    ReplyDelete
    Replies
      Reply
  5. derenJuly 10, 2023 at 1:13 AM

    başakşehir
    bayrampaşa
    beşiktaş
    beykoz
    beylikdüzü
    GG3İ

    ReplyDelete
    Replies
      Reply
  6. didemJuly 25, 2023 at 5:35 AM

    mecidiyeköy
    sakarya
    istanbul
    kayseri
    ordu

    XMUVDX

    ReplyDelete
    Replies
      Reply
Add comment
Load more...

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • ASP.NET State Management
    State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in ...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...
  • Views in ASP.NET Core MVC
    In this article, I am going to discuss Views in the ASP.NET Core MVC application. Please read our previous article before proceeding to th...
  • How to find the angle between hour and minute hands of a clock at any given time in C#
    In this article, I am going to discuss how to find the angle between the hour and minute hands of a clock at any given time in C# with an ...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape