Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpClient custom headers each request

I've noticed that using HttpClient is NOT thread safe when modifying HttpClient.DefaultRequestHeaders but I want to make as many requests as possible. I need a custom header each request (2 other headers are always the same). Also the URL changes a bit

  1. http://example.com/books/1234/readers/837
  2. http://example.com/books/854/readers/89
  3. http://example.com/books/29432/readers/238
  4. ... so on

Currently I'm creating a new HttpClient for every request but I feel like creating 10k+ HttpClients isn't the best choice here.

I'd like to make one static HttpClient with 2 DefaultRequestHeaders and use this HttpClient for every request but also add one custom header.

I want to make this as fast as possible so if you have something else I'll take it.

        Parallel.ForEach(Requests, Request =>
        {
            var Client = new HttpClient();
            Client.DefaultRequestHeaders.Clear();
            Client.DefaultRequestHeaders.Add("Header1", "Value1");
            Client.DefaultRequestHeaders.Add("Header2", "Value2");
            Client.DefaultRequestHeaders.Add("Header3", "Value for exact this request");

            var response = Client.PutAsync(new Uri($"http://example.com/books/1234/readers/837"), null); //.Result (?)
            Client.Dispose();
        });
like image 871
clearlytreated87 Avatar asked Aug 24 '26 15:08

clearlytreated87


1 Answers

Don’t use DefaultRequestHeaders for headers that don’t apply to all requests the HttpClient sends.

Also, don’t create an HttpClient per request.

You can do this easily by instead creating one HttpRequestMessage for each request, applying whatever headers you need to it, and using the same HttpClient throughout to .SendAsync() them:

using (var request = new HttpRequestMessage(HttpMethod.Put, url)
{
    request.Headers.<add here>;
    // optionally set .Content

    using (var response = await httpClient.SendAsync(request))
    {
        // ... process response
    }
}
like image 83
sellotape Avatar answered Aug 27 '26 06:08

sellotape



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!