Adding headers when using httpClient.GetAsync

后端 未结 6 1253
小鲜肉
小鲜肉 2020-11-28 04:15

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:

<         


        
6条回答
  •  无人及你
    2020-11-28 05:15

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

提交回复
热议问题