Topic: How to create an Action Filter
Description: This code shows you how to create an Action Filter that you can assign to an action(method) within a controller
Notes:
Create a class that will inherit from "ActoinFilterAttribute" and perform some time of action
Below is an example of a class the will display the amount of time a process took to the Output Window:
namespace myNameSpace.ActionFilters
{
public class SampleActionFilter : ActionFilterAttribute
{
private int _startTime, _endTime;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
_startTime = Environment.TickCount;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
_endTime = Environment.TickCount;
Debug.WriteLine("Action " +
filterContext.RouteData.GetRequiredString("action") +
" on controller " + filterContext.RouteData.GetRequiredString("controller") +
" took " + (_endTime - _startTime) + "ms");
}
}
}
Next, decorate an action (method) within your Controller and run the program and winess its execution:
namespace myNameSpace.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
Thread.Sleep(500);
return View();
}
[SampleActionFilter]
public ActionResult About()
{
return View();
}
}
}