How to do it...

We'll understand the IActionFilter interface, TypeFilter, and ServiceFilter attributes by applying a dependency injection into a controller.

  1. First, let's create an ActionFilter class only by deriving from IActionFilter:
public class MyActionFilter : IActionFilter{  public void OnActionExecuting(ActionExecutingContext context)  {    // do something before the action executes  }  public void OnActionExecuted(ActionExecutedContext context)  {    // do something after the action executes  }}
  1. To use this class as an attribute, we have to use a TypeFilter attribute, and give it this class as a parameter. We can't use MyActionFilter directly as an attribute, because it doesn't inherit from ActionFilterAttribute:
[TypeFilter(typeof(MyActionFilter))] ...

Get ASP.NET Core MVC 2.0 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.