Custom Action Filters

suggest change

Custom action filters log, save data before an action runs, or load data and store it for the request. The sample uses ASP.NET MVC’s System.Web.Mvc.ActionFilterAttribute, not the ASP.NET Core filter pipeline.

To create a custom action filter, we need to perform the following tasks:

  1. Create a class
  2. Derive it from ActionFilterAttribute

Override at least one of the following methods:

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.

The filter can be created as shown in the listing below:

using System;
using System.Diagnostics;
using System.Web.Mvc;

namespace WebApplication1
{

    public class MyFirstCustomFilter : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            //You may fetch data from database here 
            filterContext.Controller.ViewBag.GreetMessage = "Hello Foo";
            base.OnResultExecuting(filterContext);
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var controllerName = filterContext.RouteData.Values["controller"];
            var actionName = filterContext.RouteData.Values["action"];
            var message = String.Format("{0} controller:{1} action:{2}", "onactionexecuting", controllerName, actionName);
            Debug.WriteLine(message, "Action Filter Log");
            base.OnActionExecuting(filterContext);
        }
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents