Adding headers when using httpClient.GetAsync

345,306

Solution 1

When using GetAsync with the HttpClient you can add the authorization headers like so:

httpClient.DefaultRequestHeaders.Authorization 
                         = new AuthenticationHeaderValue("Bearer", "Your Oauth token");

This does add the authorization header for the lifetime of the HttpClient so is useful if you are hitting one site where the authorization header doesn't change.

Here is an detailed SO answer

Solution 2

A later answer, but because no one gave this solution...

If you do not want to set the header on the HttpClient instance by adding it to the DefaultRequestHeaders, you could set headers per request.

But you will be obliged to use the SendAsync() method.

This is the right solution if you want to reuse the HttpClient -- which is a good practice for

Use it like this:

using (var requestMessage =
            new HttpRequestMessage(HttpMethod.Get, "https://your.site.com"))
{
    requestMessage.Headers.Authorization =
        new AuthenticationHeaderValue("Bearer", your_token);
    
    await httpClient.SendAsync(requestMessage);
}

Solution 3

The accepted answer works but can got complicated when I wanted to try adding Accept headers. This is what I ended up with. It seems simpler to me so I think I'll stick with it in the future:

client.DefaultRequestHeaders.Add("Accept", "application/*+xml;version=5.1");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + authstring);

Solution 4

Sometimes, you only need this code.

 httpClient.DefaultRequestHeaders.Add("token", token);

Solution 5

Following the greenhoorn's answer, you can use "Extensions" like this:

  public static class HttpClientExtensions
    {
        public static HttpClient AddTokenToHeader(this HttpClient cl, string token)
        {
            //int timeoutSec = 90;
            //cl.Timeout = new TimeSpan(0, 0, timeoutSec);
            string contentType = "application/json";
            cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
            cl.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", token));
            var userAgent = "d-fens HttpClient";
            cl.DefaultRequestHeaders.Add("User-Agent", userAgent);
            return cl;
        }
    }

And use:

string _tokenUpdated = "TOKEN";
HttpClient _client;
_client.AddTokenToHeader(_tokenUpdated).GetAsync("/api/values")
Share:
345,306

Related videos on Youtube

Thought
Author by

Thought

Learning

Updated on February 26, 2022

Comments

  • Thought
    Thought over 1 year

    I'm implementing an API made by other colleagues with Apiary.io, in a Windows Store app project.

    They show this example of a method I have to implement:

    var baseAddress = new Uri("https://private-a8014-xxxxxx.apiary-mock.com/");
    
    using (var httpClient = new HttpClient{ BaseAddress = baseAddress })
    {
        using (var response = await httpClient.GetAsync("user/list{?organizationId}"))
        {
            string responseData = await response.Content.ReadAsStringAsync();
        }
    }
    

    In this and some other methods, I need to have a header with a token that I get before.

    Here's an image of Postman (chrome extension) with the header I'm talking about: enter image description here

    How do I add that Authorization header to the request?

  • Jason Rowe
    Jason Rowe almost 7 years
    Seems safer to not use DefaultRequestHeaders if the value changes frequently.
  • Chris Marisic
    Chris Marisic almost 7 years
    Note you very likely need requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", your_token); "Bearer" would be an invalid HTTP header
  • Wiktor Zychla
    Wiktor Zychla over 5 years
    Everyone nowadays reuses the very same instance (as per the official recommendation), this one is the actual answer then.
  • JCKödel
    JCKödel over 5 years
    -1 because HttpClient must be reusable (see aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong). If it must be reusable, setting the default request headers is a bad practice.
  • JCKödel
    JCKödel over 5 years
    -1 for not using using. ALL non managed resources MUST be disposed. It's not just about best practice, it's about not blowing up a server. Other than that, that should be the accepted answer (see my comment on the accepted answer)
  • Philippe
    Philippe over 5 years
    @JCKodel it would have added noise because you're not necessary obliged to use using but could instantiate in the constructor and dispose in the Dispose()
  • kmcnamee
    kmcnamee over 5 years
    @JCKödel That's a false assumption you are making. If you are always calling the same site with the same credentials for the lifetime of the HttpClient using the DefaultRequestHeaders saves you from having to continuously set them again with the same values. You should re-read that article it talks about using the same instance of the HttpClient, it makes no statements about default request headers being bad practice. If I am calling only one site ever with the HTTP client which in practice does happen using the DefaultRequestHeaders saves you from having to set them each time.
  • Philippe
    Philippe over 5 years
    @JCKödel A link on how using HttpClient well (without using!) aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong
  • JCKödel
    JCKödel over 5 years
    I never said use using on HttpClient (this is bad), I said on HttpRequesMessage (because it have unmanaged memory buffers for streaming that MUST be disposed after the use). The request and response are and must be disposed every request (otherwise you'll keep large memory chunks locked for a long time). The HttpClient is reusable, to an extend.
  • Bondolin
    Bondolin over 4 years
    @JCKödel why is it bad to be using the HttpClient?
  • Bondolin
    Bondolin over 4 years
    @JCKödel if you mean not using a new HttpClient for each request, I agree completely. But is there a problem with using a client for multiple requests?
  • Philippe
    Philippe over 4 years
    @Bondolin I think you misunderstood using was meaning using the keyword using(){} which dispose the instance....
  • Bondolin
    Bondolin over 4 years
    No, that's precisely what I meant. My understanding is that there is nothing wrong with using an HttpClient, doing a few requests, and then disposing of the client at the end of the using block. I do not like the approach of a static client that never gets disposed.
  • Philippe
    Philippe over 4 years
    The best is to have 1 httpClient for each api/server to query and keep it as long as possible. Which is most of the time incompatible with using using. Static could be good (at least better that multiple instances) but better is to use dependency injection. One instance kept all along the application lifetime is good.
  • Najeeb
    Najeeb almost 4 years
    @JCKödel, though you are incorrect in your assumption, I upvoted your comment, because you brought up an important point. Added greater clarity to the answer.
  • Najeeb
    Najeeb almost 4 years
    @kmcnamee, what if I need to pass two tokens?
  • Sen Jacob
    Sen Jacob over 3 years
    Github url, in case the site link expired.
  • Skrymsli
    Skrymsli almost 3 years
    This thread is another tribute to IDisposable as a failure of the language designers. You must not dispose HttpClient, but you must always dispose HttpRequestMessage. It's a recipe for disaster as developers must learn this one blown up server at a time.
  • Akash Limbani
    Akash Limbani over 2 years
    But I call API one more time, that time I face error like Cannot add value because header 'Authorization' does not support multiple values.
  • Rick
    Rick over 2 years
    @akash-limbani If you're reusing the same client, check before trying add. ``` if (!client.DefaultRequestHeaders.Contains("Authorization")) { client.DefaultRequestHeaders.Add("Authorization", "Basic " + authstring); } ```
  • AsPas
    AsPas over 2 years
    @Skrymsli that's not entirely true. You should dispose of HttpClients after you don't need them anymore! It's just that, since you can reuse the same instance, you can keep it around for later use. On the other hand, disposing of the request object is a must because the object's value is scoped in nature. So basically if you dont dispose of it, you will start piling up request objects that have no use. In a simple app you might only have 1 single HttpClient (that you likely use until your application shuts down), but you more than likely will have many, many request obejcts.
  • Skrymsli
    Skrymsli over 2 years
    @AsPas the request object is not the HttpClient and can be disposed independently. If something is IDisposable it should ALWAYS be disposed when no longer used. I should have said you must not rapidly create and dispose HttpClient, so maybe it's just HttpClient that is badly designed, but I still think IDisposable is a fail... good languages don't need it.