In this lesson, you will learn how to intercept the execution of your controller actions using Action Filters to inject cross-cutting logic like logging, validation, or performance tracking.
Understanding Action Filters
When a request hits your Web API, it travels through a series of stages. While Middleware handles the request at the global level, Action Filters allow you to hook directly into the lifecycle of a specific controller or action method. Think of them as "gatekeepers" that can execute code immediately before an action runs and immediately after it completes.
The Anatomy of an Action Filter
To create a filter, you implement the IActionFilter interface. This interface forces you to define two methods: OnActionExecuting (before the code runs) and OnActionExecuted (after the result is generated).
Consider a scenario where you want to log how long a specific action takes to process:
public class ExecutionTimeFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// Logic before the controller action runs
Console.WriteLine("Action is starting...");
}
public void OnActionExecuted(ActionExecutedContext context)
{
// Logic after the controller action has finished
Console.WriteLine("Action has completed.");
}
}
Applying the Interception
Once defined, you can apply this filter to a single controller or even a specific action method using an attribute. By decorating your controller with [TypeFilter(typeof(ExecutionTimeFilter))], the ASP.NET Core pipeline will automatically detect the filter and ensure your logic intercepts the request lifecycle.
This is incredibly powerful because it keeps your controller methods "clean." Instead of cluttering your business logic with repetitive code—like checking permissions, logging execution time, or transforming request data—you move that logic into a reusable filter. The pipeline handles the orchestration, running your filter code as a transparent layer around your actual endpoint logic. By mastering these filters, you gain fine-grained control over the request lifecycle without polluting your core application services.
Key Takeaway: Action Filters provide a declarative way to intercept the execution flow, allowing you to execute logic before and after your controller actions to maintain a clean, modular codebase.