Adding headers when using httpClient.GetAsync

2019-01-13 14:10发布

Im implementing a api made by other collegues 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

heres a image of postman( chrome extension ) with the header im talking about enter image description here

how do i add that Authorization header to the request?

5条回答
我命由我不由天
2楼-- · 2019-01-13 14:52

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);
查看更多
一纸荒年 Trace。
3楼-- · 2019-01-13 14:54

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")
查看更多
聊天终结者
4楼-- · 2019-01-13 15:10

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.

查看更多
▲ chillily
5楼-- · 2019-01-13 15:12

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

If you don't 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.

It's the right solution if you want to reuse the httpclient --which is a good practice for performance and port exhaustion problems-- and do something thread safe and without sending every time the same headers...

Use it like that:

    using( var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://your.site.com"))
    {
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", your_token);
        httpClient.SendAsync(requestMessage);
    }
查看更多
狗以群分
6楼-- · 2019-01-13 15:15

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

查看更多
登录 后发表回答