liveBook · Manning

AddHttpMessageHandler

As explained in ASP.NET Core in Action, 3e

AddHttpMessageHandler is an IHttpClientBuilder extension method that adds a delegating handler type to an HttpClient handler pipeline.

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.
CH33_F06_Lock3

Visualizes request and response flow through the custom handler and the final HttpClientHandler. section 33.4

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains handler creation, dependency-injection registration, pipeline ordering, and forwarding through SendAsync.
Examples
Uses an API-key handler with ExchangeRatesClient alongside transient error handling.
What it assumes
Assumes familiarity with C# classes and dependency injection while teaching the handler pipeline from its basic steps.
What you can do after
Build it from scratch by deriving, registering, and attaching a custom handler to an HttpClient.
How it connects
Connects DelegatingHandler, IHttpClientFactory, dependency injection, typed clients, named clients, and HttpClient pipelines.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.