পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Wednesday, March 8, 2017

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.

But many times we would like to perform some action before or after a particular operation. For achieving this functionality, ASP.NET MVC provides feature to add pre and post action behaviors on controller's action methods.

Types of Filters

ASP.NET MVC framework supports 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 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

Action Filters are additional attributes that can be applied to either a controller section or the entire controller 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 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

E.g.: 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");

        }
}

Handle Error

E.g.: Redirect application to a custom error page when an error is triggered by 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.

Authorize

E.g.: 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 this:
mvc_authorize_filter

No comments:

Post a Comment