liveBook · Manning

Custom HttpMessageHandler

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

A custom HttpMessageHandler is an application-defined HTTP pipeline component that modifies or observes requests and responses.

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.

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

How deep it goes
Explains implementation, dependency-injection registration, pipeline order, and response flow without detailing handler internals.
Examples
Demonstrates an API-key handler registered on an ExchangeRatesClient typed client.
What you can do after
Build it from scratch by deriving DelegatingHandler, overriding SendAsync(), registering the handler, and attaching it to a client.
How it connects
Connects DelegatingHandler with IHttpClientFactory, HttpClientHandler, dependency injection, authentication, and retry policies.

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.