6.60Custom DelegatingHandler
Created on Aug 17, 2026~1 min read
The following is a simple DelegatingHandler example showing how to add a custom request header before the request is sent and log the response status code after the response is received:
public class CustomHandler : DelegatingHandler{ protected override HttpResponseMessage Send(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken) { // See the async SendAsync method return base.Send(httpRequestMessage, cancellationToken); } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // Request pre-processing: add a custom request header request.Headers.Add("Custom-Header", "Value"); // Send the request and get the response var response = await base.SendAsync(request, cancellationToken); // Response post-processing: log the response status code Console.WriteLine($"Response status code: {response.StatusCode}"); return response; }}Next, register CustomHandler in the Program.cs or Startup.cs file:
// Register CustomHandler as a serviceservices.TryAddSingleton<CustomHandler>();// Enable CustomHandler for the default HttpClient clientservices.AddHttpClient() .AddHttpMessageHandler<CustomHandler>();// To enable it for a specific named HttpClient client, configure as follows// services.AddHttpClient("weixin")// .AddHttpMessageHandler<CustomHandler>();The .AddHttpMessageHandler method can be called multiple times to add multiple handlers. For example:
services.AddHttpClient(string.Empty) .AddHttpMessageHandler<CustomHandler1>() .AddHttpMessageHandler<CustomHandler2>() .AddHttpMessageHandler<CustomHandler3>();Note: Handlers execute in registration order, meaning handlers registered earlier execute first.