Action Filter In MVC

Action filter in MVC provides the option to handle the scenarios when we would like to perform an operation before and after the execution of a controller action. For this purpose, we create a custom class, which inherits the FilterAttribute class and implements the IActionFilter interface. After creating the filter, we simply apply the class name as an attribute on the controller. 
 
Here, the FilterAttribute class makes it possible to use the class as an attribute and IActionFilter interface contains two methods named OnActionExecuting and OnActionExecuted. The OnActionExecuting is executed before the controller method is executed and OnActionExecuted is called after the execution of the controller method. This kind of technique is quite helpful for the logging purposes. Thus, let's see how we can use this filter.
 
Let's start by adding a new class named MyActionFilter.cs. Now, derive this class from the FilterAttribute and the IActionFilter. Implement the  OnActionExecuting and OnActionExecuted methods and add your custom logic into the methods.Thus, the code will look as shown below.  
  1. public class MyActionFilter : FilterAttribute, IActionFilter  
  2. {  
  3.     public void OnActionExecuted(ActionExecutedContext filterContext)  
  4.     {  
  5.         //Fires after the method is executed  
  6.     }  
  7.   
  8.     public void OnActionExecuting(ActionExecutingContext filterContext)  
  9.     {  
  10.         //Fires before the action is executed  
  11.     }  
  12. }  
Simply, apply the class as an attribute on the controller. Add debuggers on both the methods as well as the controller method. 
  1. public class HomeController : Controller  
  2. {  
  3.     [MyActionFilter]  
  4.     public ActionResult Index()  
  5.     {  
  6.         return View();  
  7.     }  
  8.   
  9.     public ActionResult About()  
  10.     {  
  11.         ViewBag.Message = "Your application description page.";  
  12.         return View();  
  13.     }  
  14.   
  15.     public ActionResult Contact()  
  16.     {  
  17.         ViewBag.Message = "Your contact page.";  
  18.         return View();  
  19.     }  
  20. }  
Run the Application and debug step by step to see the order of execution of the methods. First, the OnActionExecuting will be executed, then the controller method and finally the OnActionExecuted method. 



I hope you enjoyed reading it. Happy coding.