liveBook · Manning

DelegatingHandler

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

DelegatingHandler is a .NET HttpMessageHandler base class that forwards processing to an inner handler while allowing additional behavior.

DelegatingHandler is a HttpMessageHandler base class for adding behavior around outgoing HTTP requests. It forwards processing to the next handler and can inspect or modify responses. section 33.4 section 33.5

Create and attach a custom handler in these steps:

  • Derive a handler from DelegatingHandler and override SendAsync(). section 33.4
  • Add the custom behavior, call base.SendAsync(), and return or modify the response. section 33.4
  • Register the handler with dependency injection and attach it using AddHttpMessageHandler<T>() on a named or typed client. section 33.4
  • Choose transient or singleton registration according to whether the handler requires state, and use registration order to control pipeline order. section 33.4

Adding an API key

An ApiKeyMessageHandler can inject API-key settings, add an API-KEY header to every outgoing request, and call the next handler. Register it as a transient service, then add it to an ExchangeRatesClient alongside a transient error handler. 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

Follow the request from a custom handler through the pipeline to HttpClientHandler, then follow the response back through handlers. section 33.4

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

How deep it goes
Explains derivation, SendAsync, dependency-injection registration, pipeline ordering, and request-response flow.
Examples
Demonstrates an API-key handler and its registration alongside transient error handling for ExchangeRatesClient.
What it assumes
Assumes familiarity with C# classes, asynchronous methods, dependency injection, and named or typed HttpClient clients.
What you can do after
Build custom request behavior, register it with dependency injection, and apply it to selected HttpClient pipelines.
How it connects
Connects DelegatingHandler with HttpMessageHandler, HttpClientHandler, IHttpClientFactory, dependency injection, and typed or named clients.

Also explained in

Compare how 2 books explain DelegatingHandler →

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.