Search code examples
c#windows-runtimewindows-store-appsdotnet-httpclientapiary.io

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?


Solution

  • 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