AddHttpMessageHandler<T>() adds a DelegatingHandler to a named or typed HttpClient pipeline. The handler can inspect or change outgoing requests and responses, keeping cross-cutting behavior such as authentication, logging, metrics, or retries out of business logic. section 33.4 section 33.5
Configure a custom handler in four steps:
- Derive a handler from DelegatingHandler and override SendAsync(). section 33.4
- Add the custom behavior, then call base.SendAsync() so the request continues through the remaining pipeline. section 33.4
- Register the handler with dependency injection as transient when it has state, or singleton when it does not. section 33.4
- Call AddHttpMessageHandler<T>() on the IHttpClientBuilder; registration order determines handler order. section 33.5
Adding an API key handler
builder.Services.AddTransient<ApiKeyMessageHandler>(); builder.Services.AddHttpClient<ExchangeRatesClient>() .AddHttpMessageHandler<ApiKeyMessageHandler>() .AddTransientHttpErrorPolicy(...); ApiKeyMessageHandler can read strongly typed settings, add an API-KEY header to every request, and pass the request onward. The typed client then receives both the API-key behavior and the registered transient-error behavior. section 33.4
Figure 33.6 You can use a custom HttpMessageHandler to modify requests before they’re sent to third-party APIs. Every request passes through the custom handler before the final handler (the HttpClientHandler) sends the request to the HTTP API. After the response is received, each handler gets a chance to inspect and modify the response.
Visualizes request and response flow through the custom handler and the final HttpClientHandler. section 33.4
