Search code examples
c#http-headerstokendotnet-httpclient

HttpClient DefaultRequestHeaders Authorization Exception


I have a class that has a private HttpClient. I have a DoRequest method that handles all my requests and takes a template object for the content/parameters. So far I have 2 calls. One is to retrieve a token and one is to get some other info (GetInfo). my GetInfo method will need the authorization header set so I do this before calling DoRequest:

this.Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

As soon as I started doing a Parallel.For for a load test, I start getting a An item with the same key has already been added exception, sometimes. Now I understand that the headers are stored in a dictionary and that's why I am getting the exception but I am looking for ideas on how to solve this while retaining my DoRequest design. I guess one way to solve it is to set the header in my HttpContent object but that lives in my DoRequest method and I would need to pass a Token parameter to it now. I'm not saying that's the worst thing in the world but am looking for alternatives, if any exist.


Solution

  • The way I thought this problem through is by analyzing what I wanted. I wanted to re-use HttpClient but dispose of any Authorization headers. The best way I can think to do that is to use an HttpRequestMessage and pass the Token to my DoRequest method. In my method, I do:

    HttpRequestMessage reqmsg = new HttpRequestMessage(method, uri);
    reqmsg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token ?? string.Empty);
    reqmsg.Content = formContent;