Section104.1:CustomActionFilters
We write custom action filters for various reasons. We may have a custom action filter for logging, or for saving data to database before any action execution. We could also have one for fetching data from the database and setting it as the global values of the application.
Tocreateacustomactionfilter,weneedtoperformthefollowingtasks:
- Createaclass
- InherititfromActionFilterAttributeclass
Overrideatleastoneofthefollowingmethods:
OnActionExecuting–Thismethodiscalledbeforeacontrolleractionisexecuted.
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.
Thefiltercanbecreatedasshowninthelistingbelow:
usingSystem;
usingSystem.Diagnostics;
usingSystem.Web.Mvc;
namespaceWebApplication1
{
publicclassMyFirstCustomFilter:ActionFilterAttribute
{
publicoverridevoidOnResultExecuting(ResultExecutingContextfilterContext)
{
//Youmayfetchdatafromdatabasehere filterContext.Controller.ViewBag.GreetMesssage=”HelloFoo”;base.OnResultExecuting(filterContext);
}
publicoverridevoidOnActionExecuting(ActionExecutingContextfilterContext)
{
varcontrollerName=filterContext.RouteData.Values[“controller”]; varactionName=filterContext.RouteData.Values[“action”];
varmessage=String.Format(“{0}controller:{1}action:{2}”,”onactionexecuting”,
controllerName,actionName);
Debug.WriteLine(message,”ActionFilterLog”);
base.OnActionExecuting(filterContext);
}
}
}
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024