Sunday, 21 August 2016

Action Filters in MVC

Sometimes you want to perform or inject some logic either before an execution of action method or after an execution of action method.  so to achieve this , ASP.NET MVC provides action filters.
Action filters are custom attributes that provide a declarative means to add pre-action and post-action behavior to controller action methods.

The base class fo any filter  the ASP.NET MVC framework includes a base  ActionFilterAttribute class.   This class implements both the  IActionFilter  and IResultFilter interfaces and inherits from the Filter class. 

The base ActionFilterAttribute class has the following methods that you can override:

  • OnActionExecuting This method is called before a controller action is executed.
  • OnActionExecuted This method is called after a controller action is executed.
  • OnResultExecuting This method is called before a controller action result is executed.
  • OnResultExecuted This method is called after a controller action result is executed.
There are some in build action filters in MVC:

ASP.NET MVC provides the following types of action filters:
  • Authorization filter, which makes security decisions about whether to execute an action method, such as performing authentication or validating properties of the request. The AuthorizeAttribute class is one example of an authorization filter.
  • Action filter, which wraps the action method execution. 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, which wraps execution of the ActionResult object. This filter can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is one example of a result filter.
  • Exception filter, which executes if there is an unhandled exception thrown somewhere in action method, starting with the authorization filters and ending with the execution of the result. Exception filters can be used for tasks such as logging or displaying an error page. TheHandleErrorAttribute class is one example of an exception filter.
How to implement custom action filter:

Step 1: Create a custom class and inherit with "ActionFilterAttribute" class and override its method.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace CustomActionFilter.Models
{
    public class CustomAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            Log("OnActionExecuted method call", filterContext.RouteData);
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Log("OnActionExecuting method call", filterContext.RouteData);
        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            Log("OnResultExecuted method call", filterContext.RouteData);
        }
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            Log("OnResultExecuting method call", filterContext.RouteData);
        }
        private void Log(string methodName, RouteData routeData)
        {
            var controllerName = routeData.Values["controller"];
            var actionName = routeData.Values["action"];
            var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
            Debug.WriteLine(message, "Custom Action Filter Log");
        }
    }
}

Step 2: add custom class as an attribute for a action method.

public class HomeController : Controller
    {
        //
        // GET: /Home/
        [CustomAttribute]
        public ActionResult Index()
        {
            return View();
        }

    }

Now run  the application and you will see the out put which you have mention in custom class.

No comments:

Post a Comment

Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft