ActionFilters help you to perform logic while an MVC action is executing or after an MVC action has executed.
Action filters are useful in the following scenarios:
You can create action filters by two ways:
ActionFilter
attribute.To create an inline action attribute we need to implement the IActionFilter
interface. The IActionFilter
interface has two methods: OnActionExecuted
and OnActionExecuting
. We can implement pre-processing logic or cancellation logic in these methods.
public class Default1Controller : Controller , IActionFilter
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine("Action is executing");
}
}
The problem with the inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from ActionFilterAttribute
and implement the IActionFilter
interface as shown in the below code.
public class MyActionAttribute : ActionFilterAttribute , IActionFilter
{
void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
{
Trace.WriteLine("Action Executed");
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
Trace.WriteLine("Action executing");
}
}
Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code I have decorated the Default1Controller
with the MyActionAttribute
class which was created in the previous code.
[MyActionAttribute]
public class Default1Controller : Controller
{
public ActionResult Index(Customer obj)
{
return View(obj);
}
}