Custom Action Filters In ASP.NET MVC

When request processing is going on then I pass from different levels and sometimes it is required to pass some logic on a particular stage, then filters are used. So, basically filters are used to add some logic or injecting some logic at different levels when request is processed.

There are five types of filters with ASP.NET MVC 5 and they are as follows.

  1. Authorization Filter: It is performing before or after the validating the request.
  2. Action Filter: It is performing before or after action method.
  3. Result Filter: It is performing before or after the action result.
  4. Exception Filter: It is executed if there is some exception thrown by application when performing action process. It is used to show the error page or for logging error details.

Authorization Filter

Today, we are going to learn about only Action Filters and about rest of the filters we will cover in next article.

Action Filters

It is used to execute filter logic either before the action method execution or after the action method execution. It completes some task sometimes before the action runs or after the action run. There are several tasks which should be done before or after the action execution like logging, authentication, caching, etc.

To implement action filters, you need to create custom action filters.

Custom Action Filters

Now, you are going to create a Custom Action Filter which implements the pre-processing and post-processing logic. It will inherit from ActionFilterAttribute class and also implement IActionFilter interface.

  • ActionFilterAttribute contains four important methods as in the following.
  • OnActionExecuting: It is called just before the action method is going to call.
  • OnActionExecuted: It is called just after the action method is called.
  • OnResultExecuting: It is called just before the result is executed; it means before rendering the view.
  • OnResultExecuted: It is called just after the result is executed, it means after rendering the view.

    OnResultExecuted

Now, it is time to add new class name as “CustomActionFilter.cs” which is inherited from ActionFilterAttribute and also implemented IActionFilter interface.

Let’s see an example of Custom Filter to check the user privilege to access the particular resource or not. See the following code.

Example 1

  1. using System.Web;  
  2. using System.Web.Mvc;  
  3. using Microsoft.AspNet.Identity;  
  4. using System.Web.Routing;  
  5.   
  6. namespace FilterDemo  
  7. {  
  8.     public class AuthorizationPrivilegeFilter : ActionFilterAttribute  
  9.     {  
  10.   
  11.         public override void OnActionExecuting(ActionExecutingContext filterContext)  
  12.         {  
  13.   
  14.             AuthorizationService _authorizeService = new AuthorizationService();  
  15.             string userId = HttpContext.Current.User.Identity.GetUserId();  
  16.             if (userId != null)  
  17.             {  
  18.                 var result = _authorizeService.CanManageUser(userId);  
  19.                 if (!result)  
  20.                 {  
  21.                     filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary{{ "controller""Account" },  
  22.                                           { "action""Login" }  
  23.   
  24.                                          });  
  25.                 }  
  26.             }  
  27.             else  
  28.             {  
  29.                 filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary{{ "controller""Account" },  
  30.                                           { "action""Login" }  
  31.   
  32.                                          });  
  33.   
  34.             }  
  35.             base.OnActionExecuting(filterContext);  
  36.         }  
  37.   
  38.     }  
  39. }   
Example 2
  1. public class LoggingFilterAttribute : ActionFilterAttribute  
  2. {  
  3.     public override void OnActionExecuting(ActionExecutingContext filterContext)  
  4.     {  
  5.         filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " +  
  6.             filterContext.ActionDescriptor.ActionName);  
  7.   
  8.         base.OnActionExecuting(filterContext);  
  9.     }  
  10.   
  11.     public override void OnActionExecuted(ActionExecutedContext filterContext)  
  12.     {  
  13.         if (filterContext.Exception != null)  
  14.             filterContext.HttpContext.Trace.Write("(Logging Filter)Exception thrown");  
  15.   
  16.         base.OnActionExecuted(filterContext);  
  17.     }  
  18. }  
You can see in the above code, we are overriding the OnActionExecuting method, it is because this will called before the action method executes.

OnActionExecuting

There are following way to use your Custom Action Filters.

As Global Filter

You need to add your filter globally, to add your filter to the global filter. You first need to add it on Global.asax file.
  1. protected void Application_Start()  
  2. {  
  3.     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
  4.     //otehr code  
  5.     AppConfig.Configure();  
  6. }  
You can use FilterConfig.cs which is inside the App_Start folder and as you know, App_Start is accessible globally.
  1. public class FilterConfig  
  2. {  
  3.     public static void RegisterGlobalFilters(GlobalFilterCollection filters)  
  4.     {  
  5.         filters.Add(new HandleErrorAttribute());  
  6.         filters.Add(new AuthorizationPrivilegeFilter());  
  7.     }  
  8. }  
As Controller bh

You can add filter on controller as an attribute and filter will be applicable to all the corresponding action method.
  1. [AuthorizationPrivilegeFilter]  
  2. public class StudentController : Controller  
  3. {  
  4.     // GET: Student  
  5.     public ActionResult Index()  
  6.     {  
  7.         Student model = new Student() {  
  8.             StudentId=10,  
  9.             StudentName="Mukesh Kumar",  
  10.             Address="New Delhi"  
  11.         };  
  12.         TempData["StudentDetail"] = model;  
  13.         TempData["Message"] = "This is Sudent Details using TempData";  
  14.   
  15.         return RedirectToAction("Check");  
  16.     }  
  17.     }  
As Action

If you add the action filter on particular action as an attribute then it will be applicable to only one of this action.
  1. [AuthorizationPrivilegeFilter]  
  2. public ActionResult Index()  
  3. {  
  4.     Student model = new Student() {  
  5.         StudentId=10,  
  6.         StudentName="Mukesh Kumar",  
  7.         Address="New Delhi"  
  8.     };  
  9.     TempData["StudentDetail"] = model;  
  10.     TempData["Message"] = "This is Sudent Details using TempData";  
  11.   
  12.     return RedirectToAction("Check");  
  13. }  
Thanks for reading this article, hope you enjoyed it.