Web API Filters

Filters provide a way to apply declarative base logic to the execution pipeline of an ASP.NET Web API application. This logic can be executed before or after the execution of action methods on controllers. Filters are useful for implementing cross-cutting concerns such as authentication, authorization, logging, and error handling.

Types of Filters

ASP.NET Web API defines several filter types, each targeting a specific part of the request pipeline:

Implementing Custom Filters

You can implement custom filters by creating classes that implement the appropriate filter interfaces from the System.Web.Http.Filters namespace. For example, to create an action filter, you would implement the IActionFilter interface.

Example: A Simple Action Filter

The following example demonstrates a custom action filter that logs the start and end of an action method's execution.

LoggingActionFilter.cs


using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Threading;
using System.Threading.Tasks;

public class LoggingActionFilterAttribute : ActionFilterAttribute
{
    public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
    {
        Debug.WriteLine($"Entering action: {actionContext.ActionDescriptor.ActionName}");
        await base.OnActionExecutingAsync(actionContext, cancellationToken);
    }

    public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
    {
        Debug.WriteLine($"Exiting action: {actionExecutedContext.ActionDescriptor.ActionName}");
        await base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
    }
}
            

Applying Filters

Filters can be applied globally, to specific controllers, or to individual action methods.

Global Filters

To apply a filter globally, add it to the Filters collection in your WebApiConfig.cs file.

WebApiConfig.cs


using System.Web.Http;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Other configuration...

        config.Filters.Add(new LoggingActionFilterAttribute());

        // Other configuration...
    }
}
            

Controller-Level Filters

Apply filters to an entire controller by adding the [MyFilter] attribute to the controller class.

ProductsController.cs


using System.Web.Http;

[LoggingActionFilter] // Applied to all actions in this controller
public class ProductsController : ApiController
{
    // Actions here...
}
            

Action-Level Filters

Apply filters to specific action methods by adding the [MyFilter] attribute directly above the action method.

ProductsController.cs


using System.Web.Http;

public class ProductsController : ApiController
{
    [LoggingActionFilter] // Applied only to this action
    public IHttpActionResult GetProduct(int id)
    {
        // ...
    }
}
            

Built-in Filters

ASP.NET Web API provides several built-in filters for common scenarios:

Filters are a powerful mechanism for enforcing policies and adding behavior to your Web API. Understanding their execution order and how to implement them is crucial for building robust and maintainable APIs.