本文翻譯自: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.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
標頭?
#1樓
參考:https://stackoom.com/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.com/");
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.com/"
.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");