Home » c# » c# – Concurrency issue using HttpClient and HttpRequestMessage

c# – Concurrency issue using HttpClient and HttpRequestMessage

Posted by: admin February 21, 2020 Leave a comment

Questions:

My code looks something like this:

private readonly HttpClient _httpClient;

public SomeConstructor(HttpClient httpClient){
     _httpClient = httpClient;
}

public void SomeMethod(string reqUrl, string payload){
     var result = GetResponseStringAsync(reqUrl, payload).GetAwaiter().GetResult();
     // do something with result
}

private async Task<string> GetResponseStringAsync(string reqUrl, string payload){
     using (var req = new HttpRequestMessage("POST", reqUrl)){
          using (var content = new StringContent(payload)){
               // Attach content headers here (specific for each request)

               req.Content = content;
               // Attach request headers here (specific for each request)
               // using req.Headers.TryAddWithoutValidation()

               using (var response = await _httpClient.SendAsync(req))
               {
                   return await response.Content.ReadAsStringAsync();
               }
          }
     }
}

I need to send API requests that have different, signed headers per request, otherwise I will get back 401 (Unauthorized). That said, when I send a single request, I always got 200, indicating that the authorization headers are sent correctly. However, if I send multiple requests at once (say with concurrency level set to 10), only 1 request got 200 back, whereas the other 9 got 401s. If I click on these 9 links individually, however, I got 200s for every single one of them, as expected.

It seems to me that somehow, there’s a concurrency issue that results in the proper headers not being attached to their corresponding requests, even when I create a new HttpRequestMessage for each request. HttpClient and HttpRequestMessage both are supposedly thread-safe but could someone provide an explanation as to why I’m still getting weird results when sending multiple requests at once?

How to&Answers: