WebClient UploadString(url,data)方法丢失“Content-Type”/“application / json”调用后的标题。 [英] WebClient UploadString(url, data) Method Loses "Content-Type"/"application/json" Header After Invocation.
问题描述
大家好!
我注意到 after I调用WebClient UploadString(url,data)方法,WebClient"丢失"。的 "内容类型" /"应用/ JSON"标题,但不是 "" api_key",
"< api_key>" 。报头NBSP;如果我选择重复使用WebClient,我需要检查 "Content-Type"/" application / json"标题存在并再次添加
,然后再调用 调用WebClient UploadString(url,data)方法。
I have noticed that after I invoke the WebClient UploadString(url, data) method, the WebClient "loses" the "Content-Type"/"application/json" header, but not the "api_key", "<api_key>" header. If I choose to reuse the WebClient, I need to check if the "Content-Type"/"application/json" header is present and add it again before invoking the WebClient UploadString(url, data) method.
if (!webClient.Headers.AllKeys.Contains("Content-Type"))
{
webClient.Headers.Add("Content-Type", "application/json");
}
var response = webClient.UploadString(url, data);
有没有解释?
Is there an explanation for that?
推荐答案
这在
WebClient.Headers 的文档中提到("你不应该假设标题值将保持不变,因为Web服务器和缓存可能会更改或添加标头到Web请求"",并且可以在源代码中看到:
https://referencesource.microsoft.com/#System/net/System/Net /webclient.cs,6fa3cb436d1d0456 跨度> 。可能有一些原因,可能是为了简化将标题转移到其他对象。
This is mentioned in documentation for WebClient.Headers ("You should not assume that the header values will remain unchanged, because Web servers and caches may change or add headers to a Web request") and can be seen in the sources: https://referencesource.microsoft.com/#System/net/System/Net/webclient.cs,6fa3cb436d1d0456. Probably there were some reasons, maybe to simplify transferring the headers to other objects.
顺便说一句,试试一个更简单的
webClient.Headers [" Content-Type"] = "application / json"没有
如果。
这篇关于WebClient UploadString(url,data)方法丢失“Content-Type”/“application / json”调用后的标题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!