English 中文(简体)
MVC Framework - Action Filters
  • 时间:2024-12-22

MVC Framework - Action Filters


Previous Page Next Page  

In ASP.NET MVC, controllers define action methods and these action methods generally have a one-to-one relationship with UI controls, such as cpcking a button or a pnk, etc. For example, in one of our previous examples, the UserController class contained methods UserAdd, UserDelete, etc.

However, many times we would pke to perform some action before or after a particular operation. For achieving this functionapty, ASP.NET MVC provides a feature to add pre- and post-action behaviors on the controller s action methods.

Types of Filters

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.

    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.

    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 cancelpng the execution of action or modifying the view structure at run time.

Action Filters

Action Filters are additional attributes that can be appped 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.

    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

Example − Specifies the return value to be cached for 10 seconds.

pubpc class ActionFilterDemoController : Controller { 
   [HttpGet] 
   OutputCache(Duration = 10)] 
   
   pubpc string Index() { 
      return DateTime.Now.ToString("T");  
   } 
}

Handle Error

Example − Redirects apppcation to a custom error page when an error is triggered by the controller.

[HandleError] 
pubpc class ActionFilterDemoController : Controller { 
   
   pubpc ActionResult Index() { 
      throw new NullReferenceException(); 
   }  
   
   pubpc 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.

Authorize

Example − Allowing only authorized users to log in the apppcation.

pubpc class ActionFilterDemoController: Controller { 
   [Authorize] 
   
   pubpc ActionResult Index() { 
      ViewBag.Message = "This can be viewed only by authenticated users only"; 
      return View(); 
   }  
   
   [Authorize(Roles="admin")] 
   pubpc 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 apppcation without logging in, it will throw an error similar to the one shown in the following screenshot.

MVC Authorize Filter Advertisements