【问题标题】:REST error-The request contain entity body but no Content-Type header.The infered media type application/octet-stream is not support for this resourceREST 错误-请求包含实体主体但没有 Content-Type 标头。推断的媒体类型 application/octet-stream 不支持此资源
【发布时间】:2019-04-30 03:09:49
【问题描述】:

我正在尝试发送 POST 请求。 虽然通过 POSTMAN 发送一切顺利,然后我尝试通过 C# 代码发送:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

var client = new RestClient(MY-URL);
var request = new RestRequest(Method.POST);
request.Credentials = new System.Net.NetworkCredential(ServerUsername, Password);
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("undefined", My JSON Data, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

我收到此错误:

请求包含实体主体,但没有 Content-Type 标头。此资源不支持推断的媒体类型“application/octet-stream”

我该如何解决?

【问题讨论】:

  • 您是在发送原始 JSON 还是在序列化要发送的对象模型?如果是后者,请将request.AddParameter 替换为request.AddJsonBody(model)
  • 否则添加参数时需要包含type即request.AddParameter("application/json", My JSON Data, ParameterType.RequestBody);

标签: c# rest asp.net-web-api postman


【解决方案1】:

试着写:

Content-Type: application/json; charset=UTF-8"

或添加到您的标题中:

Accept: application/json

【讨论】:

    【解决方案2】:

    在正文中添加参数会更改请求的内容类型。

    在你的例子中

    request.AddParameter("undefined", My JSON Data, ParameterType.RequestBody);
    

    覆盖之前设置的内容类型。

    如果您要序列化要发送的对象模型,请将request.AddParameter 替换为

    request.AddJsonBody(model);
    

    它将序列化并包含适当的标头信息

    否则添加参数时需要包含类型

    request.AddParameter("application/json", "My JSON Data", ParameterType.RequestBody);
    

    【讨论】:

    • 谢谢,这是我的解决方案-request.AddParameter("application/json", "My JSON Data", ParameterType.RequestBody);
    • @user7768692 如果这解决了问题,请记住将其标记为答案。
    • 我也面临同样的问题。实际上它适用于我的其他项目。这一行 "request.AddParameter("application/json", "My JSON Data", ParameterType.RequestBody);"已经在我的代码中了。但没有运气。
    • 唯一的区别,我将我的 RestSharp Libray 更新为“106.11.4”
    【解决方案3】:

    在我的例子中,我使用的是 Fiddler,不知何故我有一个额外的回车,我在 Fiddler 中看不到。

    Fiddler 在我的便签本中显示了这个:

    POST https://mywebsite/?api-version=7.3 HTTP/1.1
    AnotherHeader: 2413OL
    

    但是在粘贴到 Nodepad 之后我看到了这个:

    POST https://mywebsite/?api-version=7.3 HTTP/1.1
    
    AnotherHeader: 2413OL
    

    在记事本中去掉多余的回车,然后粘贴回Fiddler的便签本后,一切正常,415状态码消失了。

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 2014-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 2012-09-11
      • 2013-01-30
      • 2014-11-14
      相关资源
      最近更新 更多