【发布时间】:2018-12-03 15:51:11
【问题描述】:
在使用HttpClient时,我已经阅读了使用DefaultRequestHeaders设置Post请求的内容类型(例如“application/json”)的示例(例如this example)。
我试图做这样的事情,但失败了。我正在发送请求的API 抱怨它被发送了“不支持的类型”(当内容类型未设置为json 时它会说)。
然后我添加了一行,我解决了这个问题(你可以在下面的代码中看到注释的行)。
我的问题是为什么这条线是必要的?如果我包含这一行(即设置 content 的内容类型)并不会使“默认请求标头”设置变得不必要。如果有的话,这个“默认请求标头”在做什么?
(我实际上尝试并评论了与DefaultRequestHeaders 相关的行,并且没有问题。那么DefaultRequestHeaders 有什么用处?)
我的代码是:
// Get the bytes for the request, should be pre-escaped
byte[] bytes = Encoding.UTF8.GetBytes(jsonEmployeeData);
client.BaseAddress = new Uri("the address here");
// client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("customHeader", "blahblahblah");
ByteArrayContent byteContent = new ByteArrayContent(bytes); //Make a new instance of HttpContent (an abstract class that can't be instantiated)
//THIS is the solution
//byteContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json"); //If I UNCOMMENT THIS, IT WORKS!!
try
{
HttpResponseMessage response = await client.PostAsync("staff", byteContent);
Console.WriteLine(response.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Something happened, oopps!" + ex.Message);
}
Console.WriteLine("Press any key");
Console.ReadLine();
client 是HttpClient。
【问题讨论】:
-
我不确定为什么前面的方法对您不起作用,但是您是否尝试使用 fiddler 来发现两者之间的区别?如果您还没有,我强烈建议您通过 Telerik 探索提琴手 - telerik.com/fiddler。您基本上可以检查请求的请求和响应,并且它具有基于域过滤请求,标头检查等强大的功能。
标签: dotnet-httpclient httpcontent