HttpClient single instance with different authentication headers

If your headers are usually going to be the same then you can set the DefaultRequestHeaders. But you don’t need to use that property to specify headers. As you’ve determined, that just wouldn’t work if you’re going to have multiple threads using the same client. Changes to the default headers made on one thread would impact requests sent on other threads.

Although you can set default headers on the client and apply them to each request, the headers are really properties of the request. So when the headers are specific to a request, you would just add them to the request.

request.Headers.Authorization = new AuthenticationHeaderValue("bearer", bearerToken);

That means you can’t use the simplified methods that don’t involve creating an HttpRequest. You’ll need to use

public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)

documented here.


Some have found it helpful to use extension methods to isolate the code that updates the headers from the rest of a method.

Example of GET and POST methods done through an extension method that allow you to manipulate the request header and more of the HttpRequestMessage before it is sent:

public static Task<HttpResponseMessage> GetAsync
    (this HttpClient httpClient, string uri, Action<HttpRequestMessage> preAction)
{
    var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, uri);

    preAction(httpRequestMessage);

    return httpClient.SendAsync(httpRequestMessage);
}

public static Task<HttpResponseMessage> PostAsJsonAsync<T>
    (this HttpClient httpClient, string uri, T value, Action<HttpRequestMessage> preAction)
{
    var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uri)
    {
        Content = new ObjectContent<T>
            (value, new JsonMediaTypeFormatter(), (MediaTypeHeaderValue)null)
    };
    preAction(httpRequestMessage);

    return httpClient.SendAsync(httpRequestMessage);
}

These could then be used like the following:

var response = await httpClient.GetAsync("token",
    x => x.Headers.Authorization = new AuthenticationHeaderValue("basic", clientSecret));

Leave a Comment