Tuesday, May 26, 2015

Custom Action Filter in ASP.NET MVC 5


ASP.NET MVC 5 provides five different kinds of Filters. They are as follows:
  1. Authentication [Introduced in MVC5]
  2. Authorization
  3. Action
  4. Result
  5. Exception
Filters are used to inject logic at the different levels of request processing. Let us understand where at the various stages of request processing different filters get applied.
  • Authentication filter runs before any other filter or action method
  • Authorization filter runs after Authentication filter and before any other filter or action method
  • Action filter runs before and after any action method
  • Result filter runs before and after execution of any action result
  • Exception filter runs only if action methods, filters or action results throw an exception
I have tried to show the filter execution timing in context of request processing in the below diagram:
customfilterimg1
Action Filter
An action filter consists of codes that run either before or after an action runs. It can be used for tasks like logging, privileged based authorization, authentication, caching etc.
Creating a custom action filter is very easy. It can be created in four simple steps:
  1. Create a class
  2. Inherit ActionFilterAttribute class
  3. Override the OnActionExecuting method to run logic before the action method
  4. Override the OnActionExecuted method to run logic after the action method
Let us see how we can create a custom action filter. The purpose of the action filter is to find whether a logged in user belongs to a particular privileges or not. On the basis of the result, a user will access a particular action or navigate to the login action. To do this, I have created a class and extended the ActionFilterAttribute class.
As you see in the above code, the OnActionExecuting method is overridden because we want the code to execute before the action method gets executed. Once the action filter is created, it can be used in three ways:
  1. As Global filter
  2. As Controller
  3. As Action
By adding a filter to the global filter in App_Start\FilterConfig it will be available globally to the entire application.
By adding a filter to a particular Controller it will also be available to the all actions of that particular controller.
By adding a filter to a particular action it will be available to the particular action.
1
2
3
   [AuthorizationPrivilegeFilter]
        public ActionResult About()
        {

2 comments:

ASP.NET Core

 Certainly! Here are 10 advanced .NET Core interview questions covering various topics: 1. **ASP.NET Core Middleware Pipeline**: Explain the...