Adding headers when using httpClient.GetAsync

后端 未结 6 1251
小鲜肉
小鲜肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 05:20

    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

    • performance and port exhaustion problems
    • doing something thread-safe
    • not sending the same headers every time

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

提交回复
热议问题