Explain Filter Overrides in Asp.Net MVC 2022

What are Filter overrides in MVC?

“Filter overrides” is one of the critical features of ASP.NET MVC used while .NET development. Its main purpose is to exclude action, method, or controller from the controller level filter or global filter. It allows us to clear specific types of filters that might be created at the higher scopes.

Let’s say, there is a scenario where we created a global action filter or a controller-level action filter, now we have an action method on which we don’t want to use an action filter in Asp.Net MVC. In this scenario, the filter override feature is used.

In MVC, there are five types of filters available.

  1. Action filters
  2. Authentication filters
  3. Authorization filters
  4. Exception filters
  5. Result filters

Therefore, we have five filter overrides according to prior filters:

  1. OverrideActionFiltersAttribute
  2. OverrideAuthenticationAttribute
  3. OverrideAuthorizationAttribute
  4. OverrideExceptionAttribute
  5. OverrideResultAttribute

We can mark any action method with a corresponding override filter attribute that essentially clears all the filters at the controller level or global level.

How to apply the Authorization Filter at the controller level?

In this following example, we will discuss in detail the Filter Override. Here, the Authorization Filter is applied at the controller level. Thus, all the action methods of the home controller can be accessed by the Admin user only. Now, we will bypass or exclude the Authorize Filter from the “About” method.

[Authorize(Users="Admin")]  
public class HomeController : Controller  
{  
    public ActionResult Index()  
    {  
        ViewBag.Message = "iFour Technolab";  
        return View();  
    }   
    public ActionResult About()  
    {  
        return View();  
    }  
}

Here, we will mark the “About” method with the “OverrideAuthorization” attribute. Now, all the action methods of the home controller are available to access for Admin users except the “About” action method without any type of authorization.

[Authorize(Users="Admin")]  
public class HomeController : Controller  
{  
    public ActionResult Index()  
    {  
        ViewBag.Message = "Welcome to ASP.NET MVC!";  
        return View();  
    }  
    [OverrideAuthorization]  
    public ActionResult About()  
    {  
        return View();  
    }  
}  

Example

Open the Visual Studio and click Create New Project.

Figure 1: Visual Studio Home

After selecting New Project, we will select Web Templates from the left side of the panel after the selection of Web Template, we will see only one project template in that portion which is “ASP.NET Web Application”, select that.

Figure 2: Visual Studio Project Creation

After that, we will name the project “MVC5DEMO5” and click the OK button. A new popup will be shown in the same tab.

Figure 3: Visual Studio Project Selection

Here, we will choose the MVC Project template and then choose the Authentication type as Choose Individual User Accounts.

Figure 4: Selection of Authentication

When we choose this option for Authentication of application, it will be configured to use ASP.NET Identity where the User can register in the Application and sign in using the credentials. New features of MVC 5 also support Sign in via Facebook, Google, Microsoft, and Twitter. All the data are collected and stored in the SQL Server database.

When you select the Authentication type as Individual User Accounts, and click on OK, you will see a progress bar while project creation.

Figure 5: Project Created Successfully

After successfully creating the project, you will be shown Readme HTML page with links on the page.

Figure 6: Home Page

Now, we will add the Filter folder to the Project. For that, right-click on MVC5DEMO5 and select Add, and inside that select New Folder.

Figure 7: Visual Studio Project Folders

After successfully creating the folder, we will add Filters in this folder to validate whether the user has logged in to the application or not.

Now, we are going to add Filter in the Filters folder with the name UserAuthenticationFilter and it 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, if not then it will allow executing Action Method.

Here is the code snipped for 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)
        {
           
        }
    }
}

Next, we will apply the UserAuthenticationFilter Filter on HomeController. This controller is created by default when we have created a project.

Figure 8: Adding the Controller

To access controller for a user, he must have Session[“UserID”]. It wll get him to error view if the ID is found Null or empty.

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

namespace MVC5DEMO5.Controllers
{
 [UserAuthenticationFilter]
 public class HomeController : Controller
 {
  public ActionResult Index()
  {
   return View();
  }
  public ActionResult About()
  {
   ViewBag.Message = "Your application description page.";
   return View();
  }
  public ActionResult Contract()
  {
   ViewBag.Message = "Your Contact page.";
   return View();
  }
 }
}

After saving the changes, let’s run the application using the following URL:

http://localhost:xxxxx/home/Index

The following Error View screen will appear whenever we will try to open any pages among Index, About and Contact.

Figure 9: Error View

Now, we will apply the [OverrideAuthentication] filter on the About Action Method as below:

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

namespace MVC5DEMO5.Controllers
{
    [UserAuthenticationFilter]
    public class HomeController : Controlller
    {
        public ActionResult Index()
        {
            return View();
        }
        [OverrideAuthentication]
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page."
            return View();
        }
        public ActionResult Contact()
        {
                        ViewBag.Message = "Your contact page."
            return View();
        }
    }
}  

There will be three possible outcomes:

  1. If we access the Index Action Method, it will redirect to Error view as UserAuthenticationFilter is applied on Controller. It means that it is applied to all the Action Methods inside that Controller.
  2. If we access the Contact Action Method, it too will redirect to Error view as UserAuthenticationFilter is applied on Controller. It means that it is applied to all the Action Methods inside that Controller.
  3. If we access the About Action method, it will not redirect to Error view as we have applied the OveerideAction Filter on this action method.

If we want to override the Action filter then we must only apply the OverrideActionFilters but if we apply any other filter such as OverrideAuthentication or OverrideAuthorization or OverrideResultFilter or OverrideExceptionFilters, it won’t work.

Conclusion

In this article, we learned what is override in MVC, the types of overrides, and an example of overrides used in an MVC application. This will provide you with an easy and complete understanding of the Filter override procedures.

Author
Tuning an always learning and growth mindset, Harshal Suthar is a dexterous digital marketing professional with years of experience working with digital marketing, PPC, Adwords, social media marketing, and other digital services. https://www.ifourtechnolab.com