ASP.NET Core by Ken

Introduction to DelegatingHandler in ASP.NET

DelegatingHandler is a powerful mechanism in ASP.NET that enables developers to intercept and manipulate HTTP requests and responses. Functioning similarly to middleware, it allows for the implementation of cross-cutting concerns such as logging, authentication, and error handling in a modular and reusable manner.

Key Features:

  • Middleware-like Behavior: Processes HTTP requests and responses in a pipeline fashion.
  • Cross-Cutting Concerns: Ideal for tasks like logging, authentication, and error handling.
  • Reusability: Handlers can be reused across different HttpClient instances.
  • Testability: Facilitates unit testing by isolating concerns

 

Common Use Cases for DelegatingHandler

DelegatingHandler is versatile and can be employed for various purposes:

  • Authentication: Attach tokens or API keys to outgoing requests.
  • Logging: Log request and response details for monitoring and debugging.
  • Error Handling: Implement retry policies or handle specific HTTP status codes.
  • Caching: Cache responses to reduce redundant network calls.
  • Header Manipulation: Add or modify headers in requests or responses.

 

DelegatingHandler vs. Middleware

While both DelegatingHandler and middleware can process HTTP requests and responses, they serve different purposes:

  • Middleware: Operates on incoming HTTP requests to the server.
  • DelegatingHandler: Operates on outgoing HTTP requests from HttpClient.

Use middleware for server-side concerns and DelegatingHandler for client-side HTTP request processing.

AspNet
DelegatingHandler
HttpClient
Middleware
CrossCuttingConcerns
...see more

To create a custom DelegatingHandler:

  1. Inherit from DelegatingHandler:

    public class CustomHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Pre-processing logic
            var response = await base.SendAsync(request, cancellationToken);
            // Post-processing logic
            return response;
        }
    }
  2. Register the Handler:
    In ASP.NET Core, register the handler using IHttpClientFactory:

    services.AddTransient<CustomHandler>();
    services.AddHttpClient("NamedClient")
            .AddHttpMessageHandler<CustomHandler>();
...see more

Multiple DelegatingHandlers can be chained to create a pipeline:

services.AddTransient<LoggingHandler>();
services.AddTransient<AuthenticationHandler>();
services.AddHttpClient("ChainedClient")
        .AddHttpMessageHandler<LoggingHandler>()
        .AddHttpMessageHandler<AuthenticationHandler>();

In this setup, LoggingHandler processes the request first, followed by AuthenticationHandler. The order of registration determines the sequence of execution.

Comments