本文翻译自:How do you set the Content-Type header for an HttpClient request?

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/");
    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 with HttpResponseMessage , and content headers with HttpContent objects. 确保HttpRequestMessage使用请求标头, HttpResponseMessage使用响应标头, HttpContent对象使用内容标头。

How can I set the Content-Type header in a HttpClient request? 如何在HttpClient请求中设置Content-Type标头?


#1楼

参考:https://stackoom/question/io9O/如何设置HttpClient请求的Content-Type标头


#2楼

Call AddWithoutValidation instead of Add (see this MSDN link ). 调用AddWithoutValidation而不是Add (请参阅此MSDN链接 )。

Alternatively, I'm guessing the API you are using really only requires this for POST or PUT requests (not ordinary GET requests). 另外,我猜您正在使用的API实际上仅需要POST或PUT请求(而不是普通的GET请求)。 In that case, when you call HttpClient.PostAsync and pass in an HttpContent , set this on the Headers property of that HttpContent object. 在这种情况下,当您调用HttpClient.PostAsync并传递HttpContent ,请在该HttpContent对象的Headers属性上进行设置。


#3楼

The content type is a header of the content, not of the request, which is why this is failing. 内容类型是内容的标头,而不是请求的标头,这就是失败的原因。 AddWithoutValidation as suggested by Robert Levy may work, but you can also set the content type when creating the request content itself (note that the code snippet adds "application/json" in two places-for Accept and Content-Type headers): 由Robert Levy建议的AddWithoutValidation可能有效,但是您也可以在创建请求内容本身时设置内容类型(请注意,代码段在两个位置为“ Accept”和“ Content-Type”标头添加了“ application / json”):

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://example/");
client.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
                                    Encoding.UTF8, 
                                    "application/json");//CONTENT-TYPE header

client.SendAsync(request)
      .ContinueWith(responseTask =>
      {
          Console.WriteLine("Response: {0}", responseTask.Result);
      });

#4楼

对于那些没有看到约翰对卡洛斯解决方案发表评论的人...

req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

#5楼

If you don't mind a small library dependency, Flurl.Http [disclosure: I'm the author] makes this uber-simple. 如果您不介意小的库依赖关系, 那么Flurl.Http [公开:我是作者]使这个超级简单。 Its PostJsonAsync method takes care of both serializing the content and setting the content-type header, and ReceiveJson deserializes the response. 它的PostJsonAsync方法负责序列化内容和设置content-type标头,而ReceiveJson反序列化响应。 If the accept header is required you'll need to set that yourself, but Flurl provides a pretty clean way to do that too: 如果需要accept标头,则需要自己设置,但Flurl也提供了一种非常干净的方法:

using Flurl.Http;

var result = await "http://example/"
    .WithHeader("Accept", "application/json")
    .PostJsonAsync(new { ... })
    .ReceiveJson<TResult>();

Flurl uses HttpClient and Json.NET under the hood, and it's a PCL so it'll work on a variety of platforms. Flurl在后台使用HttpClient和Json.NET,它是PCL,因此可以在各种平台上工作。

PM> Install-Package Flurl.Http

#6楼

try to use TryAddWithoutValidation 尝试使用TryAddWithoutValidation

  var client = new HttpClient();
  client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");

更多推荐

如何设置HttpClient请求的Content-Type标头?