Set Authorization/Content-Type headers when call HTTPClient.PostAsync

前端 未结 3 744
忘了有多久
忘了有多久 2020-12-30 05:31

Where can I set headers to REST service call when using simple HTTPClient?

I do :

HttpClient client = new HttpClient();
var values = new Dictionary&         


        
3条回答
  •  悲&欢浪女
    2020-12-30 06:13

    The other answers do not work if you are using an HttpClientFactory, and here's some reasons why you should. With an HttpClientFactory the HttpMessages are reused from a pool, so setting default headers should be reserved for headers that will be used in every request.

    If you just want to add a content-type header you can use the alternate PostAsJsonAsync or PostAsXmlAsync.

    var response = await _httpClient.PostAsJsonAsync("account/update", model);
    

    Unfortunately I don't have a better solution for adding authorization headers than this.

    _httpClient.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization.ToString(), $"Bearer {bearer}");
    

提交回复
热议问题