Custom Action Filters
suggest changeCustom 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:
- Create a class
- 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);
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents