Filters in ASP.NET Web API are a powerful feature that allows you to run custom logic before or after an action method executes. They can be used for various purposes, such as logging, authentication, authorization, caching, and exception handling. Filters help you separate cross-cutting concerns from your business logic, making your code cleaner and more maintainable.
Types of Filters
ASP.NET Web API supports several types of filters, each serving a different purpose:
- Authorization Filters: These filters are used to implement authentication and authorization logic. They run before any other filters and can prevent access to the action method.
- Action Filters: These filters allow you to run code before and after an action method executes. They are useful for logging, modifying the action result, or performing additional processing.
- Exception Filters: These filters handle exceptions that occur during the execution of an action method. They allow you to log errors and return custom error responses.
- Result Filters: These filters run after the action method has executed but before the response is sent to the client. They can be used to modify the response or perform additional processing.
Using Filters in ASP.NET Web API
Below are examples of how to create and use different types of filters in an ASP.NET Web API application.
1. Creating an Authorization Filter
An authorization filter checks whether a user is authorized to access a specific resource. Here’s an example of a custom authorization filter:
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
public class CustomAuthorizationFilter : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
// Check if the user is authenticated
if (!actionContext.Request.Headers.Authorization?.Scheme.Equals("Bearer") ?? true)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
Applying the Authorization Filter
You can apply the custom authorization filter to a controller or action method using the [CustomAuthorizationFilter]
attribute:
[CustomAuthorizationFilter]
public class ProductsController : ApiController
{
[HttpGet]
public IHttpActionResult Get()
{
return Ok(new List<string> { "Product1", "Product2" });
}
}
2. Creating an Action Filter
An action filter allows you to run code before and after an action method executes. Here’s an example of a custom action filter that logs the execution time of an action:
using System.Diagnostics;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
public class LogExecutionTimeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
// Start timing
actionContext.Request.Properties["StartTime"] = Stopwatch.StartNew();
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// Stop timing
var stopwatch = (Stopwatch)actionExecutedContext.Request.Properties["StartTime"];
stopwatch.Stop();
var executionTime = stopwatch.ElapsedMilliseconds;
// Log the execution time (you can use a logging framework)
System.Diagnostics.Debug.WriteLine($"Execution Time: {executionTime} ms");
}
}
Applying the Action Filter
You can apply the action filter to a controller or action method using the [LogExecutionTimeFilter]
attribute:
[LogExecutionTimeFilter]
public class ProductsController : ApiController
{
[HttpGet]
public IHttpActionResult Get()
{
return Ok(new List<string> { "Product1", "Product2" });
}
}
3. Creating an Exception Filter
An exception filter allows you to handle exceptions that occur during the execution of an action method. Here’s an example of a custom exception filter that logs exceptions and returns a custom error response:
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
public class CustomExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
// Log the exception (you can use a logging framework)
// LogError(context.Exception);
// Set the response
context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An unexpected error occurred.");
}
}
Applying the Exception Filter
You can apply the custom exception filter globally in the WebApiConfig.cs
file:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new CustomExceptionFilter());
// Other configuration settings...
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
4. Creating a Result Filter
A result filter allows you to modify the response before it is sent to the client. Here’s an example of a custom result filter that adds a custom header to the response:
using System.Net.Http;
using System.Web.Http.Filters;
public class CustomResultFilter : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// Add a custom header to the response
actionExecutedContext.Response.Headers.Add("X-Custom-Header", "MyHeaderValue");
}
}
Applying the Result Filter
You can apply the result filter to a controller or action method using the [CustomResultFilter]
attribute:
[CustomResultFilter]
public class ProductsController : ApiController
{
[HttpGet]
public IHttpActionResult Get()
{
return Ok(new List<string> { "Product1", "Product2" });
}
}
Conclusion
Filters in ASP.NET Web API provide a powerful way to implement cross-cutting concerns such as logging, authentication, and error handling. By creating custom filters, you can encapsulate reusable logic and apply it across your application, leading to cleaner and more maintainable code. Understanding how to use filters effectively will enhance the functionality and robustness of your Web API applications.