In this article, we will cover ASP.NET Core IActionFilter.

So, Let's get started.

What are Filters in ASP.NET Core?

Filters are used to add cross-cutting concerns, such as Logging, Authentication, Authorization, Exception Handling, Caching, etc.

Filters allow us to execute cross-cutting logic in the following ways:

  1. Before an HTTP request is handled by a controller action method.
  2. After an HTTP request is handled by a controller action method.
  3. After the response is generated but before it is sent to the client.

Action Filters in ASP.NET Core

The Action Filters in the ASP.NET Core are executed before and after an action method is executed. They perform tasks like Logging, Modifying the Action’s Arguments, or Altering the Action’s Result.

IActionFilter

In ASP.NET Core, IActionFilter is an interface that allows you to inspect and manipulate the actions being executed in your application. It provides methods that can be used to add custom behavior before and after an action method is invoked. While it's a powerful tool for cross-cutting concerns, there are both advantages and disadvantages to using IActionFilter.

Advantages of IActionFilter

Disadvantages of IActionFilter

Example

TimeActionFilter logs the execution time of action methods. The OnActionExecuting method captures the start time, while OnActionExecuted calculates the elapsed time and logs it.

// Create TimeActionFilter
 
  public class TimeActionFilter : IActionFilter
    {
        private Stopwatch stopwatch;

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            stopwatch = Stopwatch.StartNew();
            Debug.WriteLine($"Stopwatch Started");
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            stopwatch.Stop();
            var elapsedMilliseconds = stopwatch.ElapsedMilliseconds;
            // log the elapsed time
            Debug.WriteLine($"Action '{filterContext.ActionDescriptor.DisplayName}' executed in {elapsedMilliseconds} ms");
        }
    }
// Register the filter in Startup.cs 

public void ConfigureServices(IServiceCollection services) 
  {
	services.AddControllers(options => 
	 {
	     options.Filters.Add(typeof(TimeActionFilter)); 
	 });  
  }

TimeActionFilter