Understanding MVC Action Filters


MVC action methods allows to process the incoming request and perform necessary action on it. However, if there is need where in you would want to process the request before it hits any action methods or perform post processing after action method is executed. This is where MVC Action filters play’s vital role in pre-processing or post processing the request. Additionally, filters allows to inject custom logic at different stages of action method execution.



MVC Filter
    



MVC Action Filters Types

There are various inbuilt filters provided by MVC framework.

Authorization filter

    
     This allows to validate security attributes of user associated with request. For example, if you would like to validate whether user is authenticated or not, does he has necessary roles to perform requested operation. For example: Authorize attribute. In below example, user with only admin role will be allowed to invoke action method: DeleteUser.


public class HomeController : Controller
    {
        [Authorize (Roles="Admin")]
        public ActionResult DeleteUser (string userId)
        {
            //Call User DeleteService
        }
    }


Action Filter


Intercepts the incoming request to the action method, performs data validation, provide additional input to the action method or cancel execution method. This kind of filters are useful when you want execute some business logic prior to execution actual controller method.

Result Filter


Filters result returned by action methods. This is primarily required if you want to cache the response of any action method or modify the http response. One example for this is: OutputCache Attribute.

public class HomeController: Controller
{
        [OutputCache(Duration=60)]
        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }
}


    Exception Filter


These filters are useful for catching and logging any exception generated during execution of action method.  HandleError attribute is a good example for Exception filter. This can be applied on controller or action method. In the below example HandleError attribute has parameter "view", which allows us to show new contact page instead of regular error page in case of errors.

  public class HomeController : Controller
    {
        [HandleError(View="NewContactPage")]
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

    }


Creating Custom Action Filters


MVC framework provides bunch of filters, but in some cases it is better to build our own filter that suits our own custom requirements. In such cases, it can be simply achieved by overriding the virtual methods of abstract class: ActionFilterAttribute.

ActionFilterAttribute class has four Virtual methods.
  •  OnActionExecuting : Allows to inject code before action method starts execution .
  •  OnActionExecuted: Allows to inject code after action method is executed
  • OnResultExecuting: Allows to inject code before action method builds action object
  • OnResultExcuted: Allows to inject code after action method builds action object.


Example of Custom Action filters

Let us create a custom filter that allows us log the input parameters that are passed to the action methods. In order to implement this, we will create a CustomLogFilterAttribute class that inherits from ActionFilterAttibute class. To intercept input request, we will override the method :OnActionExecuting.

Implementation of Custom Action Filter:

   public class CustomLogFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Trace.Write("Action Method executing :" +
                filterContext.ActionDescriptor.ActionName);

            filterContext.HttpContext.Trace.Write("Parameters:");
            foreach(var param in filterContext.ActionParameters)
            {
                filterContext.HttpContext.Trace.Write("Key=" +param.Key);
                if (param.Value != null)
                    filterContext.HttpContext.Trace.Write("Value=" + param.Value.ToString());
            }

            base.OnActionExecuting(filterContext);
        }
    }

Adding Custom Filter attribute to the controller:

  public class HomeController : Controller
    {
        [CustomerLogFilterAttribute]
        public ActionResult Index(int? id)
        {
            ViewBag.Message = "Your contact page.";
            return View();
        }

    }


Testing Custom Action filters


Let us test our CustomLogFilter with request: Home/Index/2. This request will initiate invocation of action method: Index by passing parameter value =2. Before action method gets called CustomLogFilter will Intercepts the request and logs it.

MVC Filter log


Order of Execution of Action filters

Let say if we want to apply more than one custom filter on our action method and we would like to define order for each one of them so that they are executed in predefined order. Yes, this is possible.
The order of execution of action filter can be customized using order property that is available for each action filter attribute. In the below example, authorize filter gets applied first and HandleError gets applied at last.

  public class HomeController : Controller
    {
        [CustomerLogFilterAttribute(Order=2)]
        [HandleError(Order=3)]
        [Authorize(Order=1)]
        public ActionResult Index(int? id)
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

    }




This is all I have for now . Hope you liked this article.  Please share your comments.

Keep watching this blog for more useful article.

Happing Coding 
MK

No comments: