What are Action Filters in MVC?

Category: C SharpWhat are Action Filters in MVC?
Editor">Editor Staff asked 2 years ago

What are Action Filters in MVC?

1 Answers
Editor">Editor Staff answered 2 years ago

to modify the way in which 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.
     
  • 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.

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.)
 
Output Cache
 
Code Example
 
Specifies the return value to be cached for 10 seconds.

 

  1. publicclassActionFilterDemoController: Controller  
  2. {  
  3.     [HttpGet]  
  4.     OutputCache(Duration = 10)]  
  5. publicstringIndex()  
  6. {  
  7.     returnDateTime.Now.ToString(“T”);  
  8.   
  9. }  
  10. }