skip to content

In ASP.NET Core, how does a DelegatingHandler add an auth header to a typed HttpClient's requests, and which DI scope does it live in?

level: middleimportance: should knowfreq 52%

answer

  1. outgoing middleware around SendAsync
  2. AddTransient, then AddHttpMessageHandler<T>
  3. first added runs outermost
  4. a separate handler scope, not the request's
  5. InnerHandler must be null

basics

~20 s

Derive from DelegatingHandler, set the header in SendAsync and call base.SendAsync; register it transient and chain AddHttpMessageHandler<T>() on the client. The factory resolves it from its own handler scope, which lives as long as the handler chain, not the incoming request.

solid answer

~40 s

A `DelegatingHandler` is outgoing middleware: override `SendAsync`, add `request.Headers.Authorization` (or an API-key header), then `return await base.SendAsync(request, ct)`. Register it with `builder.Services.AddTransient<RatesAuthHandler>()` and attach it with `.AddHttpMessageHandler<RatesAuthHandler>()` on the client's builder; handlers run in the order added, the first one outermost. The factory resolves the handler from a **separate DI scope it creates per handler chain**, and that scope lives as long as the chain, about the two-minute `HandlerLifetime`, not one incoming request. So a scoped service injected into the handler is not the request's instance. For per-request data such as the caller's own token, read `IHttpContextAccessor` or pass values through `HttpRequestMessage.Options`. Registering the handler as a singleton breaks on the next rebuild: the builder throws because its `InnerHandler` is already set.

code

csharp · 16 lines
csharp
public sealed class RatesAuthHandler(IRatesTokenCache tokens) : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        string token = await tokens.GetTokenAsync(cancellationToken); // refreshed when near expiry
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        return await base.SendAsync(request, cancellationToken);
    }
}

// Program.cs
builder.Services.AddSingleton<IRatesTokenCache, RatesTokenCache>();
builder.Services.AddTransient<RatesAuthHandler>();
builder.Services.AddHttpClient<ShippingRatesClient>(c => c.BaseAddress = new Uri("https://rates.example.com/"))
    .AddHttpMessageHandler<RatesAuthHandler>();

go deeper

for a junior

Recall the three steps: derive from DelegatingHandler and override SendAsync, register it transient, then chain AddHttpMessageHandler on the client.

for a middle

Explain handler order, why handlers must be transient, and that the factory resolves them from its own scope tied to the handler chain.

for a senior

Show how you keep per-request data out of long-lived handler scopes, refresh tokens inside SendAsync and debug the reused-handler exception.

for a principal

Judge where outgoing auth lives across many clients, shared handlers versus per-client ones, and how token caching is owned and observed.

## Outgoing middleware `HttpClient` sends every request through a chain of **message handlers**. A `DelegatingHandler` is one link: it receives the `HttpRequestMessage`, can change it, passes it on with `base.SendAsync`, and can inspect or replace the `HttpResponseMessage` on the way back. `IHttpClientFactory` lets you declare that chain per client name, in the same spirit as the inbound middleware pipeline. In a web shop that prices delivery through a shipping-rates provider, the provider wants a bearer token on every call. Putting that in a handler keeps the typed client's methods free of auth code. ## Wiring it up 1. Write the handler: derive from `DelegatingHandler`, override `SendAsync`, set `request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token)`, then await `base.SendAsync(request, cancellationToken)`. 2. Register it: `builder.Services.AddTransient<RatesAuthHandler>()`. The `AddHttpMessageHandler<THandler>()` documentation states the handler type must be registered as a **transient** service. 3. Attach it: `builder.Services.AddHttpClient<ShippingRatesClient>(...).AddHttpMessageHandler<RatesAuthHandler>()`. 4. Add more if needed. Handlers run **in registration order**: the first one added is outermost, so it sees the request first and the response last. Other overloads take a factory delegate, `AddHttpMessageHandler(() => new RatesAuthHandler(...))` or one that receives the `IServiceProvider`; the delegate must return a **new** instance each time. ## Why transient, and why not singleton When the factory builds a chain it sets each handler's `InnerHandler` to the next link. A handler instance can therefore belong to only one chain. If the handler were a singleton, the next chain the factory builds (after `HandlerLifetime` expires, or for another client name) would receive the same object with `InnerHandler` already set, and the builder throws an `InvalidOperationException` saying delegating handler instances must not be reused or cached. ## The handler's own DI scope The factory creates a **separate DI scope for every handler chain** and resolves the handlers from it. That scope: - is not the ASP.NET Core request scope and shares no scoped instances with it; - lives as long as the chain, roughly the `HandlerLifetime` (two minutes by default), and is disposed with it; - is therefore shared by every request that uses the chain during that time. The consequence: a handler that takes a scoped `ICurrentUser` in its constructor gets one instance created when the chain was built and reuses it for minutes, across many users. That is fine for things that are effectively application-wide, such as `IOptions<RatesOptions>` holding a static API key or a token cache, and wrong for anything per request. | Data the header needs | Where the handler gets it | |---|---| | A fixed API key from configuration | constructor-injected `IOptions<T>` | | A machine-to-machine token that expires | a singleton token cache injected into the handler | | The incoming user's token or a correlation value | `IHttpContextAccessor.HttpContext` at call time, or `HttpRequestMessage.Options` set by the caller | `IHttpContextAccessor` needs `builder.Services.AddHttpContextAccessor()`, and its `HttpContext` is null outside a request, for example in a background service, so handle that case. `HttpRequestMessage.Options` replaced the obsolete `Properties` dictionary. ## Where your handler sits next to the built-in ones The factory adds two logging handlers to every chain after your configuration has run: - a scope handler, logging under `System.Net.Http.HttpClient.<name>.LogicalHandler`, inserted **first**, so it wraps all of your handlers and measures the whole pipeline; - a request handler, logging under `System.Net.Http.HttpClient.<name>.ClientHandler`, added **last**, right next to the primary handler, so it records the request as it leaves, after your auth handler has run. Header values in these logs are redacted by default (every value); `RedactLoggedHeaders` lets you choose which ones stay hidden. That default is worth keeping for an `Authorization` header. ## Simpler alternatives - For a header that never changes, `client.DefaultRequestHeaders` in the `AddHttpClient` configuration delegate is enough; no handler needed. - `ConfigureAdditionalHttpMessageHandlers` gives you the whole handler list for one client when you need to reorder or remove handlers. - Handlers that retry or time out belong to the resilience handlers, which are added to the same chain. ## Common mistakes - Registering the handler `AddScoped` and expecting the request's scoped services; the factory's handler scope is a different scope either way. - Forgetting to call `base.SendAsync`, so the request never reaches the network. - Reading an expired token once in the constructor; the handler lives for minutes, so fetch or refresh the token inside `SendAsync`.

  • Two handlers are added with AddHttpMessageHandler<LoggingHandler>() and then AddHttpMessageHandler<RatesAuthHandler>(). Which sees the Authorization header?
    Handlers run in registration order, the first one outermost. `LoggingHandler` sees the request before `RatesAuthHandler` adds the header, so it will not log it; swap the order if the logging handler must see the final request. On the way back the order reverses.
  • How would you forward the incoming user's bearer token to the downstream API?
    Inject `IHttpContextAccessor` (registered with `AddHttpContextAccessor()`) into the handler and read the token from `HttpContext` inside `SendAsync`, not in the constructor, because the handler outlives a single request. Guard against a null `HttpContext` when the client is also used outside requests.

  • Registers the DelegatingHandler as a singleton to save allocations
  • Believes the handler shares the incoming request's DI scope
  • Reads a per-request value in the handler's constructor
  • Thinks the last handler added runs first on the request
  • Forgets to call base.SendAsync in the override