Monday, June 18, 2012

MVC - Action Filter

Action Filtering in MVC :
Sometimes we want to perform logic either before an action method is called or after an action method runs. MVC provides action filters to perform these tasks.
Action filters are custom attributes perform pre-action and post-action behavior to controller action methods.
  MVC Action Filter Types

  • Authorization filter : It makes security decisions about whether to execute an action method
  • Action filter :  This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.
  • Result filter :  This filter can perform additional processing of the result,:
  • Exception filter :  It executes if there is an unhandled exception thrown somewhere in action method.

 Action filter is an attribute that implements the abstract  FilterAttribute class

AuthorizeAttribute :  Action method with AuthorizeAttribute mean that access to current action method is restricted to users who are both authenticated and authorizedif we apply AuthorizeAttribute  to controller  then all action methods in the controller are restricted.
Properties :

Order    Gets or sets the order in which the action filters are executed.
Roles     Gets or sets the user roles.
TypeId  Gets the unique identifier for this attribute.
Users    Gets or sets the authorized users.


        //Attribute limits access to users who are logged in
        [Authorize]
        public ActionResult AuthorizeUsers()
        {
            return View();
        }

        //Attribute limits access to users who has Role ADMIN and DIRECTOR       
        [Authorize(Roles = "ADMIN , DIRECTOR")]
        public ActionResult Admin_Director()
        {
            return View();
        }

        //Attribute limits access to special users USER1 and USER1 only.  
        [Authorize(Users = "USER1 , USER2")]
        public ActionResult SpecialUsers()
        {
            return View();
        }





OutputCacheAttribute :  Action methods with OutputCacheAttribute  is used to cache output .If we mark a controller with OutputCacheAttribute attribute, the output of all action methods in the controller will be cached.

[OutputCache(Duration = 10, VaryByParam = "Id")]      
public ActionResult About()
  {
     ViewData["Message"] = "This page was cached at " + DateTime.Now;
     return View();
  }


Cache Profile

We can also set a cache profile in the Web.config file instead of setting cache values individually in pages. 
  <system.web>
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add name="HomeProfile" duration="30" varyByParam="*" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
  </system.web>


[OutputCache(CacheProfile = "HomeProfile", Duration = 10)]
public ActionResult About()
   {
      ViewData["Message"] = "This page was cached at " + DateTime.Now;
      return View();
   }


 HandleErrorAttribute attribute  specify how to handle an exception that is thrown by an action method.
Properties:
·         ExceptionType :  Specifies the exception type or types that the filter will handle. If this property is not specified, the filter handles all exceptions.
·         View :  Specifies the name of the view to display.
·         Master :  Specifies the name of the master view to use.
·         Order. Specifies the order in which the filters are applied, if more than one HandleErrorAttribute filter is possible for a method.

Order Property

Order property to an integer value that specifies a priority from -1 (highest priority) to any positive integer value.
The greater the integer value is, the lower the priority of the filter is. The Order property follows these rules:
1.     Filters that are applied to a controller automatically apply to every action method in that controller.
2.     Filters that are applied to the controller run before filters that are applied to an action method, as long as the order numbers are the same.
3.     Filters with the same order number are applied in an undetermined order.
4.     If no order number is specified, the order number is -1. This means that the filter is applied before any other HandleErrorAttribute filters, except other filters whose order is also -1.
5.     The first HandleErrorAttribute filter that can handle the exception will be called, after which exception handling stops for that exception.




  //when this method called then default Error view is displayed because ther eis no parameters.
        [HandleError]
        public ActionResult method1()
        {
            throw new ApplicationException();
        }

        // This method specify when erroroccer then CustomError View display.
        // The ExceptionType parameter specifies that this filter should be called only for a                NotImplementedException error.
        [HandleError(View = "CustomError", ExceptionType = typeof(NotImplementedException))]
        public ActionResult ThrowNotImplemented()
        {
            throw new NotImplementedException();
        }


No comments :

Post a Comment