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:
- Authorization Filters: Execute before any other filter. They are used to determine if the request is authorized to proceed.
- Action Filters: Execute before and after an action method executes. They can modify the request or response before it's processed by the action, or after the action has executed but before the result is rendered.
- Result Filters: Execute before and after the action result executes. This is useful for modifying the response content or headers.
- Exception Filters: Execute when an unhandled exception occurs in the Web API pipeline. They are used for global exception handling and logging.
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:
AuthorizeAttribute
: For authentication and authorization.RequireHttpsAttribute
: Ensures requests are made over HTTPS.ValidateModelAttribute
: Validates model state before an action executes.HandleErrorAttribute
: Handles exceptions globally.