What is the usage of DelegatingHandler in Asp.Net webAPI C#?

In ASP.NET Web API, a DelegatingHandler is a type of HTTP message handler that forms a chain of handlers to process HTTP requests and responses. Each handler in the chain can perform operations on the request before passing it to the next handler, and then process the response when it comes back up the chain.

The DelegatingHandler class allows you to create custom server-side message handlers that can intercept, modify, or handle HTTP requests and responses globally across your Web API application. This is useful for implementing cross-cutting concerns like logging, authentication, caching, or request validation.

Syntax

To create a custom message handler, inherit from System.Net.Http.DelegatingHandler and override the SendAsync method −

public class CustomHandler : DelegatingHandler {
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, 
        CancellationToken cancellationToken) {
        // Process request
        var response = await base.SendAsync(request, cancellationToken);
        // Process response
        return response;
    }
}

How It Works

The delegating handler pattern works as a pipeline where each handler can −

  • Process the request message before passing it to the next handler

  • Call base.SendAsync() to send the request to the inner handler

  • Receive the response from the inner handler asynchronously

  • Process the response before returning it to the caller

DelegatingHandler Chain Flow Handler 1 Handler 2 Handler 3 Controller Request Request Request Response Response Response Each handler can process both request and response Request flows right ? Response flows left ?

Using DelegatingHandler for Request Processing

Example - Logging Handler

using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

public class LoggingHandler : DelegatingHandler {
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken) {
        
        Debug.WriteLine("LoggingHandler processing the request");
        Console.WriteLine($"Request: {request.Method} {request.RequestUri}");
        
        // Call the inner handler
        var response = await base.SendAsync(request, cancellationToken);
        
        Debug.WriteLine("LoggingHandler processing the response");
        Console.WriteLine($"Response: {response.StatusCode}");
        
        return response;
    }
}

public class TestController : ApiController {
    [HttpGet]
    public string Get() {
        return "Hello from API";
    }
}

public class Program {
    public static void Main(string[] args) {
        // This demonstrates the handler logic
        // In actual Web API, handlers are registered in WebApiConfig
        Console.WriteLine("DelegatingHandler Example");
        Console.WriteLine("Handler would process: GET /api/test");
        Console.WriteLine("Request: GET http://localhost/api/test");
        Console.WriteLine("Response: 200 OK");
    }
}

The output of the above code is −

DelegatingHandler Example
Handler would process: GET /api/test
Request: GET http://localhost/api/test
Response: 200 OK

Using DelegatingHandler to Short-Circuit Requests

A delegating handler can skip the inner handler and create a response directly −

Example - Authentication Handler

using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

public class AuthenticationHandler : DelegatingHandler {
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken) {
        
        // Check for authorization header
        if (!request.Headers.Contains("Authorization")) {
            // Create unauthorized response directly
            var response = new HttpResponseMessage(HttpStatusCode.Unauthorized) {
                Content = new StringContent("Authorization header is required")
            };
            
            // Return completed task without calling inner handler
            return Task.FromResult(response);
        }
        
        // Continue to next handler if authorized
        return base.SendAsync(request, cancellationToken);
    }
}

public class Program {
    public static async Task Main(string[] args) {
        var handler = new AuthenticationHandler();
        var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/api/test");
        
        // Simulate the handler processing
        Console.WriteLine("Testing request without Authorization header:");
        
        // This would normally be handled by the Web API pipeline
        var mockResponse = new HttpResponseMessage(HttpStatusCode.Unauthorized) {
            Content = new StringContent("Authorization header is required")
        };
        
        Console.WriteLine($"Status: {mockResponse.StatusCode}");
        Console.WriteLine($"Content: {await mockResponse.Content.ReadAsStringAsync()}");
    }
}

The output of the above code is −

Testing request without Authorization header:
Status: Unauthorized
Content: Authorization header is required

Common Use Cases

  • Logging and monitoring − Track request/response details

  • Authentication and authorization − Validate tokens or credentials

  • Caching − Cache responses to improve performance

  • Rate limiting − Control request frequency from clients

  • Request/response transformation − Modify headers or content

Conclusion

DelegatingHandler in ASP.NET Web API provides a powerful way to implement cross-cutting concerns by creating a chain of handlers that can process HTTP requests and responses. It enables clean separation of concerns and reusable components for common operations like logging, authentication, and caching across your entire Web API application.

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

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements