ASP.NET MVC Action Filters
Here we look at creating custom Action Filters in ASP.NET MVC.
ActionFilterAttribute
When creating new custom action filters in ASP.NET MVC we need to create a class which inherits from ActionFilterAttribute. From this we can implement the following methods:
OnActionExecuting
OnActionExecuted
OnResultExecuting
OnResultExecuted
Here is a sample class which implements these methods:
using System.Web.Mvc;
namespace MVC_Practise.Controllers
{
public class MyFirstCustomActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// do something
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
// do something
base.OnActionExecuted(filterContext);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// do something
base.OnResultExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
// do something
base.OnResultExecuted(filterContext);
}
}
}
With our newly ceated custom action filter we can now apply it to individual action methods or an entire controller classes (in which case every action method will use the attribute):
[MyFirstCustomActionFilter]
public ActionResult About()
{
return View();
}
Applying our custom action filter to an action method called About results in the following order of methods firing:
OnActionExecuting
About
OnActionExecuted
OnResultExecuting
OnResultExecuted