HttpMessageHandler is the building block behind HttpClient’s outbound request pipeline. HttpClient coordinates the call, while the final HttpClientHandler opens the connection and sends the request. section 33.2.1
Handlers run in sequence: each can modify an outgoing request, then inspect the response as it returns. This makes the pipeline useful for cross-cutting concerns such as logging, metrics, authentication, and transient-error handling. section 33.2.1 section 33.0
Use IHttpClientFactory to manage the handler pipeline instead of repeatedly creating and disposing its underlying handler.
- Register the factory with builder.Services.AddHttpClient(). section 33.2.1
- Create an HttpClient through factory.CreateClient(), then configure its base address and call the remote API. section 33.2.1
- Let the factory manage handler lifetimes to avoid socket exhaustion while allowing DNS changes to be respected. section 33.5
A factory-created client
Register IHttpClientFactory, inject it into an endpoint, call factory.CreateClient(), set BaseAddress to https://example.com/rates/, and request latest. The response can then be checked with EnsureSuccessStatusCode() and read as text. section 33.2.1
Figure 33.4 Each HttpClient contains a pipeline of HttpMessageHandlers. The final handler is an HttpClientHandler, which makes the connection to the remote server and sends the HTTP request. This configuration is similar to the ASP.NET Core middleware pipeline, and it allows you to make cross-cutting adjustments to outgoing requests.
The figure shows HttpClientMessageHandlers arranged as an outbound pipeline, ending with HttpClientHandler, and compares the arrangement with ASP.NET Core middleware. section 33.2.1
