Custom Action Filters in ASP.NET MVC 5

Example Code: https://drive.google.com/file/d/1XFZdb_MtHAsoqe4mQG3_gx5q-K1SnUSJ/view?usp=sharing
Just like a built in attribute we can also create custom action filters , in this article we will create custom action filter step by step.
In this example we will create a custom action filter which when applied will generate the log of that action (name of action, controller name, datetime) in database table.
Step 1 : Create a table in database with name ALog as follows –

Step 2: Create a entity Model using DbFirst Approach for ALogTbl as follows –

Step 3: Create ASP.NET MVC Web Application with Test controller with following Actions –
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult Contact()
{
return View();
}
}
Step 4: Create CustFilter folder to create a custom filter and define a class ALog in it.
To create a Custom Action filter we need to define a class which inherits from ActionFilterAttribute, then override the method OnActionExecuting or OnActionExecuted. OnActionExecuting method will be executed just before the execution of the action. OnActionExecuted method will be executedafter execution of the the action.
For this example override the OnActionExecuting method and write the following code to create the log of the Action and Controller in ALogTbl.
public class ALog :ActionFilterAttribute
{
PracticeDBEntities entity = new PracticeDBEntities();
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ALogTbl rec = new ALogTbl();
rec.ActionName = filterContext.ActionDescriptor.ActionName;
rec.ControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
rec.LogDateTime = DateTime.Now;
entity.ALogTbls.Add(rec);
entity.SaveChanges();
}
}
Step 5: Now apply the ALog filter to the actions from the test controller or on on TestController as follows –
namespace ActionFilterEx.Controllers
{
[ALog]
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
return View();
}
}
Ste 6 : No call the actions as per requirements and it will log the data in ALogTbl and check ALogTbl will get as follows –
