Action Filters:
- This filter will be called before and after the action starts executing and after the action has executed. We can put our custom pre-processing and post-processing logic in this filter.
- Now to implement this filter we need to create a custom filter attribute class and implement the
IActionFilterfilter interface. This interface provides us two methodsOnActionExecutingandOnActionExecutedwhich will be called before and after the action gets executed respectively.
public class CustomActionAttribute : FilterAttribute, IActionFilter { void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext) { filterContext.Controller.ViewBag.OnActionExecuted = "IActionFilter.OnActionExecuted filter called"; } void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { filterContext.Controller.ViewBag.OnActionExecuting = "IActionFilter.OnActionExecuting filter called"; } }
Result Filters:
- This filter will execute before and after the result of the action method has been executed. We can use this filter if we want some modification to be done in the action's result.
- To implement the result filters we need to create a custom filter attribute class and implement the
IResultFilterinterface. this interface provides two methodsOnResultExecutingandOnResultExecutedwhich will be called before and after the action result respectively.
public class CustomResultAttribute : FilterAttribute, IResultFilter { void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext) { filterContext.Controller.ViewBag.OnResultExecuted = "IResultFilter.OnResultExecuted filter called"; } void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext) { filterContext.Controller.ViewBag.OnResultExecuting = "IResultFilter.OnResultExecuting filter called"; } }