问题:
I'm trying to set the Content-Type
header of an HttpClient
object as required by an API I am calling. 我正在尝试根据我正在调用的API设置HttpClient
对象的Content-Type
标头。
I tried setting the Content-Type
like below: 我尝试如下设置Content-Type
:
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://example.com/");
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
// ...
}
It allows me to add the Accept
header but when I try to add Content-Type
it throws the following exception: 它允许我添加Accept
标头,但是当我尝试添加Content-Type
它将引发以下异常:
Misused header name. 标头名称滥用。 Make sure request headers are used with
HttpRequestMessage
, response headers withHttpResponseMessage
, and content headers withHttpContent
objects. 确保HttpRequestMessage
使用请求标头,HttpResponseMessage
使用响应标头,HttpContent
对象使用内容标头。
How can I set the Content-Type
header in a HttpClient
request? 如何在HttpClient
请求中设置Content-Type
标头?
解决方案:
参考一: https://stackoom.com/question/io9O/如何设置HttpClient请求的Content-Type标头参考二: https://oldbug.net/q/io9O/How-do-you-set-the-Content-Type-header-for-an-HttpClient-request
来源:oschina
链接:https://my.oschina.net/u/3797416/blog/4341457