在使用 HttpClient
执行 GET
时,有没有一种方法可以显式设置 Content-Type
header 值?
我意识到这违反了 1.1 协议(protocol),但我正在使用不符合它的 API,并且我需要设置一个 Content-Type
header 。
我试过了,没有用...
using (var httpClient = new HttpClient())
{
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.com");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded+v1.3");
await httpClient.SendAsync(httpRequestMessage)
}
我在添加 TryAddWithoutValidation
后检查了 DefaultRequestHeaders
,它似乎没有设置 Content-Type
值。
如果我尝试设置 httpRequestMessage 的内容类型(通过设置 httpRequestMessage.Content = ...
,我会收到以下错误:
Cannot send a content-body with this verb-type.
有没有一种方法可以使用 HttpClient 为 GET
操作显式设置 Content-Type
?
最佳答案
根据我的发现,我得出结论,HttpClient 在协议(protocol)规则方面非常严格。我还通过实现 DLL 进行了反射(reflect),但我找不到任何表明它允许违反协议(protocol)的内容。
GET 请求不应该有内容类型 header ,并且 HttpClient 正在执行该规则。
我认为当您尝试设置内容类型 header 时的异常消息是 self 描述的:
System.InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
此外,如果您使用设置内容主体,您还会收到一条 self 描述的消息:
System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
既然您愿意违反 GET 请求的 HTTP 规则,我很确定您唯一的选择是坚持使用限制较少的 WebClient,它适用于这种情况。
关于c# - 为 HttpClient 中的 Get 操作显式设置内容类型 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26109650/