[c#] Adding headers when using httpClient.GetAsync

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?

The answer is


You can add whatever headers you need to the HttpClient.

Here is a nice tutorial about it.

This doesn't just reference to POST-requests, you can also use it for GET-requests.


Sometimes, you only need this code.

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

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);
    httpClient.SendAsync(requestMessage);
}

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")

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);

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to windows-runtime

Adding headers when using httpClient.GetAsync Convert a List<T> into an ObservableCollection<T> Setting Authorization Header of HttpClient Allowing Untrusted SSL Certificates with HttpClient

Examples related to windows-store-apps

"Permission Denied" trying to run Python on Windows 10 Adding headers when using httpClient.GetAsync Signtool error: No certificates were found that met all given criteria with a Windows Store App? Setting button text via javascript Getting content/message from HttpResponseMessage Synchronously waiting for an async operation, and why does Wait() freeze the program here Where do I mark a lambda expression async?

Examples related to dotnet-httpclient

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body? Custom header to HttpClient request Adding headers when using httpClient.GetAsync HttpClient - A task was cancelled? How to get content body from a httpclient call? Pass multiple complex objects to a post/put Web API method Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern Why is HttpClient BaseAddress not working? Make Https call using HttpClient Deciding between HttpClient and WebClient

Examples related to apiary.io

Adding headers when using httpClient.GetAsync