ActionFilters in MVC

From Logic Wiki
Jump to: navigation, search


An action filter is an attribute that you can apply to a controller action -- or an entire controller -- that modifies the way in which the action is executed.

“ActionFilters” helps you to perform logic while MVC action is executing or after a MVC action has executed.

ActionFilter1.jpg

Action filters are useful in the following scenarios:-

  1. Implement post-processinglogic beforethe action happens.
  2. Cancel a current execution.
  3. Inspect the returned value.
  4. Provide extra data to the action.

You can create action filters by two ways:-

  • Inline action filter.
  • Creating an “ActionFilter” attribute.

To create a inline action attribute we need to implement “IActionFilter” interface.The “IActionFilter” interface has two methods “OnActionExecuted” and “OnActionExecuting”. We can implement preprocessing 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 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 “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 “MyActionAttribute” class which was created in the previous code.

[MyActionAttribute]
public class Default1Controller : Controller
{
  public ActionResult Index(Customer obj)
  {
  return View(obj);
  }
}