Properly using HttpClient

HttpClient is meant to be used as a singleton, ideally using a single instance for your entire application. This has a few implications:

  1. You shouldn’t use DefaultRequestHeaders for things like authorization, as those change from one request to another. Instead, build an HttpRequestMessage and send it using HttpClient’s SendAsync method
var message = new HttpRequestMessage(HttpMethod.Post, requestUri)
{
    Content = content
};

message.Headers.Add("Accept", "application/json");
message.Headers.Add("Authorization", $"Bearer {token}");

client.SendAsync(message);
  1. You can have multiple instances of HttpClient, but ideally they should share a single request handler in order to pool connections (but really, just set the headers on the message and not directly on the client)
using HttpClientHandler handler = new HttpClientHandler();

async Task WorkWithApiA()
{
    using var client = new HttpClient(handler, false);
    client.DefaultRequestHeaders.Add("X-Secret-Auth-Token", "foo");

    await client.GetAsync("/");
    // ...
}

async Task WorkWithApiB()
{
    using var client = new HttpClient(handler, false);
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "foo");

    await client.GetAsync("/");
    // ...
}

– via this GitHub issue