A custom HttpMessageHandler adds reusable behavior to an HttpClient pipeline. It can attach authentication headers automatically, observe responses, or handle cross-cutting concerns such as logging and metrics. section 33.4 section 33.5
Build and connect a custom handler in these steps:
- Derive a class from DelegatingHandler and override SendAsync(). section 33.4
- Add the custom behavior, call base.SendAsync(), and let the remaining pipeline process the request. section 33.4
- Register the handler with dependency injection as transient when it has state, or singleton when it does not. section 33.4
- Attach it to a named or typed client with AddHttpMessageHandler<T>(); registration order determines pipeline order. section 33.4
Adding an API key to every request
An ApiKeyMessageHandler can receive API settings through IOptions, add an API-KEY header in SendAsync(), and call the next handler. Register it with dependency injection, then add it to an ExchangeRatesClient typed client. The final HttpClientHandler sends the request; handlers can inspect or modify the response on the way back.
