Filter Overrides in ASP.Net MVC 5

Introduction

ASP.NET MVC 5 has arrived with a very important feature called Filter Overrides. Using the Filter Overrides feature, we can exclude a specific action method or controller from the global filter or controller level filter. In other words, Filter Overrides allows us to clear certain types of filters that are created at higher scopes.

For example, if we created a controller-level action filter or global action filter, now I have an action method on which I do not want to action filter. In this case, the Filter Override feature is very useful.

As we know there are the following five types of filters available with MVC:

  • Authentication filters
  • Authorization filters
  • Action filters
  • Result filters
  • Exception filters

So we have five type filter overrides corresponding to this:

  • OverrideAuthenticationAttribute
  • OverrideAuthorizationAttribute
  • OverrideActionFiltersAttribute
  • OverrideResultAttribute
  • OverrideExceptionAttribute

We can mark any action method with an override filter attribute that essentially clears all filters in an upper scope (in other words controller level or global level).

Example

In the following example, the Authorize Filter is applied at the controller level. So, all the action methods of the Home controller can be accessed by the Admin user only. Now I want to exclude or bypass the Authorize Filter from the "About" method.

  1. [Authorize(Users="Admin")]  
  2. public class HomeController : Controller  
  3. {  
  4.     public ActionResult Index()  
  5.     {  
  6.         ViewBag.Message = "Welcome to ASP.NET MVC!";  
  7.         return View();  
  8.     }   
  9.     public ActionResult About()  
  10.     {  
  11.         return View();  
  12.     }  
  13. }  

So in this case we can mark this "About" method with the “OverrideAuthorization” attribute. Now all the action methods of the home controller can be accessed by the Admin user except the "About" method. We can access the "About" action method without any authorization.

  1. [Authorize(Users="Admin")]  
  2. public class HomeController : Controller  
  3. {  
  4.     public ActionResult Index()  
  5.     {  
  6.         ViewBag.Message = "Welcome to ASP.NET MVC!";  
  7.         return View();  
  8.     }  
  9.     [OverrideAuthorization]  
  10.     public ActionResult About()  
  11.     {  
  12.         return View();  
  13.     }  
  14. }  

Note: The OverrideAuthorizationAttribute does not work properly with MVC version 5.0 due to some internal bug. This bug was resolved in MVC version 5.1 (preview).

Conclusion

Filter Overrides in ASP.NET MVC 5 are very useful when we are implementing a global or controller level filter and we do not want to apply an action filter on some Action methods in the controller. This feature is useful for removing the headache of applying filters for each and every action where we need to exclude only a few actions.