What are the different types of filters in C# ASP.NET WebAPI?

Filters in ASP.NET Web API provide a way to inject additional logic at different stages of request processing. They enable cross-cutting concerns such as authentication, authorization, logging, and caching without cluttering your controller logic. Filters can be applied declaratively using attributes or programmatically, offering flexibility in how you handle these concerns.

Web API supports several types of filters, each serving a specific purpose in the request pipeline. Understanding these filter types helps you choose the right approach for implementing various functionalities in your API.

Types of Filters

Web API Filter Pipeline Authentication Authorization Action Exception (if errors occur) Override (can modify behavior of other filters) Request Flow Direction ? Authentication verifies identity ? Authorization checks permissions ? Action executes before/after method ? Exception handles unhandled errors

Authentication Filter

Authentication filters validate user credentials and establish user identity. They implement the IAuthenticationFilter interface and execute first in the filter pipeline −

public class BasicAuthenticationFilter : IAuthenticationFilter {
    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) {
        // Authentication logic here
    }
    
    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) {
        // Challenge logic here
    }
}

Authorization Filter

Authorization filters check if an authenticated user has permission to access a resource. They implement IAuthorizationFilter and run after authentication −

public class CustomAuthorizationFilter : AuthorizeAttribute {
    public override void OnAuthorization(HttpActionContext actionContext) {
        // Authorization logic here
    }
}

Action Filter

Action filters execute logic before and after action methods. They use OnActionExecuting and OnActionExecuted methods −

public class LogActionFilter : ActionFilterAttribute {
    public override void OnActionExecuting(HttpActionContext actionContext) {
        // Execute before action
    }
    
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) {
        // Execute after action
    }
}

Exception Filter

Exception filters handle unhandled exceptions thrown during action execution, except for HttpResponseException

public class GlobalExceptionFilter : ExceptionFilterAttribute {
    public override void OnException(HttpActionExecutedContext context) {
        // Exception handling logic
    }
}

Override Filter

Override filters allow you to bypass other filters for specific actions, providing granular control over filter behavior −

[OverrideAuthentication]
public IHttpActionResult GetPublicData() {
    // This action overrides controller-level authentication
}

Filter Application Levels

Filters can be applied at three different levels −

Level Scope Example
Global All controllers and actions WebApiConfig.cs registration
Controller All actions in a controller Attribute on controller class
Action Specific action method Attribute on action method

Example Implementation

Here's a complete example showing how to implement and use an authorization filter −

using System;
using System.Web.Http;

namespace DemoWebApplication.Controllers {
    public class DemoController : ApiController {
        [Authorize]
        public IHttpActionResult Get() {
            return Ok(new { message = "Authorized access successful", timestamp = DateTime.Now });
        }

        [AllowAnonymous]
        public IHttpActionResult GetPublic() {
            return Ok(new { message = "Public access - no authorization required" });
        }
    }
}

// Custom Authorization Filter Example
public class ApiKeyAuthorizationAttribute : AuthorizeAttribute {
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) {
        var request = actionContext.Request;
        var apiKey = request.Headers.GetValues("X-API-Key").FirstOrDefault();
        
        // Simple API key validation (use proper validation in production)
        return apiKey == "your-secret-api-key";
    }
}

When accessing the Get method without proper authorization, you'll receive a 401 Unauthorized response. The GetPublic method uses [AllowAnonymous] to bypass the controller-level authorization.

Global Filter Registration

You can register filters globally in WebApiConfig.cs

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Global exception filter
        config.Filters.Add(new GlobalExceptionFilter());
        
        // Global authorization
        config.Filters.Add(new AuthorizeAttribute());
    }
}

Conclusion

Web API filters provide a clean, reusable way to implement cross-cutting concerns like authentication, authorization, logging, and exception handling. By understanding the different filter types and their execution order, you can build robust APIs with proper separation of concerns and maintainable code architecture.

Updated on: 2026-03-17T07:04:36+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements