docs icon indicating copy to clipboard operation
docs copied to clipboard

Document how to implement HttpClient's delegating handlers

Open mariusz96 opened this issue 1 year ago • 0 comments

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:

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<HttpResponseMessage> 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

mariusz96 avatar Aug 09 '24 20:08 mariusz96