【发布时间】:2019-03-12 08:54:08
【问题描述】:
我尝试从 C# (.NET Core 2.2.104) 向外部 Web 服务发出带有 application/json 的 HTTP POST 请求。
我已经阅读了 SO 中的所有类似问题并编写了以下代码:
SignXmlRequestDto requestBody = new SignXmlRequestDto(p12, model.SignCertPin, model.Data);
string json = JsonConvert.SerializeObject(requestBody);
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = ncanNodeUrl,
Headers =
{
{ HttpRequestHeader.ContentType.ToString(), "application/json" }
},
Content = new StringContent(JsonConvert.SerializeObject(json))
};
var response = await httpClient.SendAsync(httpRequestMessage);
string responseString = await response.Content.ReadAsStringAsync();
我收到来自服务的错误,它说:“无效的标头 Content-Type。请将 Content-Type 设置为 application/json”。这里有趣的是,如果我模拟 Postman 的这个请求,那么一切正常,我得到了成功的响应。
更新:正如@Kristóf Tóth 所建议的,我将代码修改为:
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = ncanNodeUrl,
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
var response = await httpClient.SendAsync(httpRequestMessage);
string responseString = await response.Content.ReadAsStringAsync();
但它仍然给我同样的错误信息。
【问题讨论】:
-
HttpRequestHeader.ContentType.ToString()?? -
@PanagiotisKanavos,在这个答案中建议stackoverflow.com/a/53451542
-
没有被接受或反对,这是有原因的。
Content-Type是初学者的内容标题。在StringContent构造函数中传递内容类型,或者在内容对象上设置它 -
使用 Fiddler 或其他调试代理并捕获实际发送的内容。在 StringContent 构造函数中传递内容类型是每个人发布 JSON 请求的方式。邮递员请求是什么样的?您的查询有何不同?