MVC Framework - Action Filters

In ASP.NET MVC, controllers define action methods and these action methods generally have a one-to-one relationship with UI controls, such as clicking a button or a link, etc. For example, in one of our previous examples, the UserController class contained methods UserAdd, UserDelete, etc.
However, many times we would like to perform some action before or after a particular operation. For achieving this functionality, ASP.NET MVC provides a feature to add pre- and post-action behaviors on the controller's action methods.
ASP.NET MVC framework supports the following action filters −
Action Filters − Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.
Action Filters − Action filters are used to implement logic that gets executed before and after a controller action executes. We will look at Action Filters in detail in this chapter.
Authorization Filters − Authorization filters are used to implement authentication and authorization for controller actions.
Authorization Filters − Authorization filters are used to implement authentication and authorization for controller actions.
Result Filters − Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
Result Filters − Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.
Exception Filters − Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
Exception Filters − Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors.
Action filters are one of the most commonly used filters to perform additional data processing, or manipulating the return values or cancelling the execution of action or modifying the view structure at run time.
Action Filters are additional attributes that can be applied to either a controller section or the entire controller to modify the way in which an action is executed. These attributes are special .NET classes derived from System.Attribute which can be attached to classes, methods, properties, and fields.
ASP.NET MVC provides the following action filters −
Output Cache − This action filter caches the output of a controller action for a specified amount of time.
Output Cache − This action filter caches the output of a controller action for a specified amount of time.
Handle Error − This action filter handles errors raised when a controller action executes.
Handle Error − This action filter handles errors raised when a controller action executes.
Authorize − This action filter enables you to restrict access to a particular user or role.
Authorize − This action filter enables you to restrict access to a particular user or role.
Now, we will see the code example to apply these filters on an example controller ActionFilterDemoController. (ActionFilterDemoController is just used as an example. You can use these filters on any of your controllers.)
Example − Specifies the return value to be cached for 10 seconds.
public class ActionFilterDemoController : Controller { 
   [HttpGet] 
   OutputCache(Duration = 10)] 
   
   public string Index() { 
      return DateTime.Now.ToString("T");  
   } 
}
Example − Redirects application to a custom error page when an error is triggered by the controller.
[HandleError] 
public class ActionFilterDemoController : Controller { 
   
   public ActionResult Index() { 
      throw new NullReferenceException(); 
   }  
   
   public ActionResult About() { 
      return View(); 
   } 
} 
With the above code, if any error happens during the action execution, it will find a view named Error in the Views folder and render that page to the user.
Example − Allowing only authorized users to log in the application.
public class ActionFilterDemoController: Controller { 
   [Authorize] 
   
   public ActionResult Index() { 
      ViewBag.Message = "This can be viewed only by authenticated users only"; 
      return View(); 
   }  
   
   [Authorize(Roles="admin")] 
   public ActionResult AdminIndex() { 
      ViewBag.Message = "This can be viewed only by users in Admin role only"; 
      return View(); 
   } 
}
With the above code, if you would try to access the application without logging in, it will throw an error similar to the one shown in the following screenshot.

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    42 Lectures 
     18 hours 

 SHIVPRASAD KOIRALA

    57 Lectures 
     3.5 hours 

 University Code

    55 Lectures 
     4.5 hours 

 University Code

    40 Lectures 
     2.5 hours 

 University Code

    140 Lectures 
     9 hours 

 Bhrugen Patel
 Print
 Add Notes
 Bookmark this page