dotnet / dotnet/docs

Document how to implement HttpClient's delegating handlers

Open
#42,098 0 comments 0 reactions 0 assignees View on GitHub
:watch: Not Triaged dotnet-fundamentals/svc
Dominant language
No language data
Stars
4.8k
Forks
6.1k
Avg merge
19h 10m
Merged PRs (30d)
268

Description

### Type of issue

Missing information

### Description

The docs do not have a basic example on how to implement HttpClient's delegating handlers without dependency injection, something like:
```csharp
private static readonly HttpClient HttpMessageHandler =
new HttpClient(
new ValidateHeaderHandler(
new HttpClientHandler()));

public class ValidateHeaderHandler : DelegatingHandler
{
public ValidateHeaderHandler(HttpMessageHandler innerHandler) // This constructor is hard to discover.
: base(innerHandler)
{
}

protected override async Task SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!request.Headers.Contains("X-API-KEY"))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent(
"The API key header X-API-KEY is required.")
};
}

return await base.SendAsync(request, cancellationToken);
}
}
```

This would be even more useful considering that the docs somehow recommend a static instance and there's soo much boilerplate around HttpClient usage everywhere.

### Page URL

https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient

### Content source URL

https://github.com/dotnet/docs/blob/main/docs/fundamentals/networking/http/httpclient.md

### Document Version Independent Id

857f2b65-3e05-2cb7-9820-05dddad22605

### Article author

@IEvangelist

### Metadata

* ID: 4e2c563b-3150-f2a1-2afa-711cf3c022bf
* Service: **dotnet-fundamentals**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.