Filter Overrides in ASP.NET MVC 5 Step by Step

Introduction

Filter Overrides is yet another new feature in MVC 5, In project we apply filter mostly on global level and controller level right in this part if we do not want filter on some of Action Method in side this Controller then .

It's the real question?

One solution is there we are not going to apply filter on controller level, we can do apply filter on every single Action Method will not apply filter on particular action Method on which we do not want any filter, but if it is large project then doing this thing is not possible will lead to bug in product.

To overcome this kind scenario in MVC they have provided Filter Overrides Attribute.

Type of Filter Overrides

  1. [OverrideAuthentication]
  2. [OverrideAuthorization]
  3. [OverrideActionFilters]
  4. [OverrideResultFilters]
  5. [OverrideExceptionFilters]

These are filter which we need to apply on particular Action method to override specific Filter.

Create New Asp.Net MVC Application

From Visual studio 2015 IDE Start page click on "New Project" link.

After clicking on "New Project" link a new dialog will pop up.

In that we are going to select web templates from left pane after selecting web template, we find only one project template in it "ASP.NET Web Application" just select that.

After selecting this project template next we are going to name project as "MVC5DEMO5" and clicking on the OK button a new dialog will pop up with Name "New ASP.NET Project" for selecting project Templates.

In this dialog we are going to choose MVC project template and then we are going to choose Authentication type for doing that just click on Change Authentication button, a new dialog will pop up with name "Change Authentication" here we are going to choose Individual User Accounts .

Note: - Individual User Accounts

If you choose this option for Authentication of application then your application will be configured to use ASP.NET identity [ASP.NET Membership] where User register in the application and then sign in using credentials and also User sign in via social accounts such as Facebook, Twitter, Google, Microsoft and other providers. All user data will be stored in SQL server database.

After selecting Authentication type as Individual User Accounts click on OK Button.

It will show progress bar while it is creating project.

After creating project it will show Readme html page with use links on that page.

After creating project first thing we are going add Filter folder in Project.

For adding Folder just right click on "MVC5DEMO5" and then select Add à and inside that select "New Folder".

After adding Filter folder the next thing we are going add Filters in this folder to validate User is Logged in to application or not.

Adding Authentication Filter

We are going to add Filter in filters folder with name UserAuthenticationFilter and this filter will inherit a class FilterAttribute and IAuthenticationFilter, and in this filter we are just going to check Session is IsNullOrEmpty if it is NULL or Empty then we are going to redirect it to Error View else if it is not NULL or Empty then it will allow to execute Action Method.

Below is Code Snippet of UserAuthenticationFilter

using System;
using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace MVC5DEMO5.Filters
{
    public class UserAuthenticationFilter : FilterAttribute, IAuthenticationFilter 
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
            if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserID"])))
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "Error"
                };

            }
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
           
        }
    }
}

In next step we are going to apply UserAuthenticationFilter Filter on HomeController this Controller is created by default when we have created project.

In this step we are going to apply going to apply UserAuthentication Filter to Home controller after applying this filter.

Applying UserAuthentication Filter on HomeController

The User who is going to access this controller must have Session["UserID"] if it is NULL or empty then it is going to redirect it to Error View.

Now let's Save and Run this Project and access URL:- http://localhost:####/home/index

It will redirect it to Error View as show below.

Meanwhile if we are going to access URL: - http://localhost:3025/Home/About

It will redirect it to Error View as show below.

Meanwhile if we are going to access URL: - http://localhost:3025/Home/Contact

It will redirect it to Error View as show below.

Applying OverrideAuthentication Filter on About Action Method

In this part we are going to apply [OverrideAuthentication] filter on About Action Method.

Scenario 1:- If we are going to access Index Action Method still it is going to redirect to Error View because UserAuthenticationFilter is applied on Controller it means it is applied on all Action Methods inside that Controller.

Scenario 2:- If we are going to access Contact Action Method still it is going to redirect to Error View because UserAuthenticationFilter is applied on Controller it means it is applied on all Action Methods inside that Controller.

Scenario 3:- Now we are going to access About Action Method it will not redirect to Error View because we have applied [OverrideAuthentication] Filter on this Action Method it will override UserAuthentication Filter and this Action Method will be access to all.

Now let's Save and Run this Project and access URL: - http://localhost:####/home/index

It will redirect it to Error View as show below.

Meanwhile if we are going to access URL: - http://localhost:3025/Home/Contact

It will redirect it to Error View as show below.

But now we are going to access About Action Method it will be Accessible because we have applied [OverrideAuthentication] Filter on it.

Note: - if we want to override Authentication filter then must only apply [OverrideAuthentication] filter but if we apply other filter such [OverrideAuthorization] or [OverrideActionFilters] or [OverrideResultFilters] or [OverrideExceptionFilters] will not work on it.

Adding Authorization Filter

We are going to add Filter in filter folder with name UserAuthorizationFilter and this filter will inherit a class FilterAttribute and IAuthorizationFilter Interface, and in this filter we are just going to check Session is IsNullOrEmpty if it is NULL or Empty then we are going to redirect it to Error View else if it is not NULL or Empty then it will allow to execute Action Method.

Below is Code Snippet of UserAuthorizationFilter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC5DEMO5.Filters
{
    public class UserAuthorizationFilter : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserID"])))
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "Error"
                };

            }
        }
    }
}

In next step we are going to apply UserAuthorization Filter on HomeController this Controller is created by default when we have created project.

Scenario 1:- If we are going to access Index Action Method still it is going to redirect to Error View because UserAuthorizationFilter is applied on Controller it means it is applied on all Action Methods inside that Controller.

Scenario 2:- If we are going to access Contact Action Method still it is going to redirect to Error View because UserAuthorizationFilter is applied on Controller it means it is applied on all Action Methods inside that Controller.

Scenario 3:- Now we are going to access About Action Method it will not redirect to Error View because we have applied [OverrideAuthorization] Filter on this Action Method it will override UserAuthorizationFilter and this Action Method will be access to all.

Now let's Save and Run this Project and access URL: - http://localhost:####/home/index

It will redirect it to Error View as show below.

Meanwhile if we are going to access URL: - http://localhost:3025/Home/Contact

It will redirect it to Error View as show below.

But now we are going to access About Action Method it will be Accessible because we have applied [OverrideAuthorization] Filter on it.

Note: - if we want to override Authorization filter then must only apply [OverrideAuthorization] filter but if we apply other filter such [OverrideAuthentication] or [OverrideActionFilters] or [OverrideResultFilters] or [OverrideExceptionFilters] will not work on it.

Adding Action Filter

We are going to add Filter in filter folder with name UserActionFilter and this filter will inherit a class ActionFilterAttribute , and in this filter we are just going to check Session is IsNullOrEmpty if it is NULL or Empty then we are going to redirect it to Error View else if it is not NULL or Empty then it will allow to execute Action Method.

Below is Code Snippet of UserActionFilter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC5DEMO5.Filters
{
    public class UserActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserID"])))
            {
                filterContext.Result = new ViewResult
                {
                    ViewName = "Error"
                };

            }
        }
    }
}

In next step we are going to apply UserAction Filter on HomeController this Controller is created by default when we have created project.

Applying OverrideAuthentication Filter on About Action Method

In this part we are going to apply [OverrideActionFilters] filter on About Action Method.

Scenario 1:- If we are going to access Index Action Method still it is going to redirect to Error View because UserActionFilter is applied on Controller it means it is applied on all Action Methods inside that Controller.

Scenario 2:- If we are going to access Contact Action Method still it is going to redirect to Error View because UserActionFilter is applied on Controller it means it is applied on all Action Methods inside that Controller.

Scenario 3:- Now we are going to access About Action Method it will not redirect to Error View because we have applied [OverrideAction] Filter on this Action Method it will override UserActionFilter and this Action Method will be access to all without authentication.

Now let's Save and Run this Project and access URL: - http://localhost:####/home/about

If we directly access about action method it will allow access because we have applied [OverrideAction] Filter on About Action Method show below.

And meanwhile if access other Action method in same controller then it will not allow access to it as show below.

Note: - if we want to override Action filter then must only apply [OverrideActionFilters] filter but if we apply other filter such [OverrideAuthentication] or [OverrideAuthorization] or [OverrideResultFilters] or [OverrideExceptionFilters] will not work on it.

Adding Result Filter and Exception Filter

In similar way if we want to override Result filter or Exception filter then we need to apply [OverrideResultFilters] or [OverrideExceptionFilters] on the Action Method where you need to Override.

How to apply Result filter and Exception filter

In this series we have learnt how to use Filter override attribute feature which was new in MVC 5.

+91-22-66752917
+91 9967590707
questpond@questpond.com / questpond@yahoo.com