【问题标题】:Why I am getting 415 for this request为什么我为此请求收到 415
【发布时间】:2017-11-09 14:56:04
【问题描述】:

我有一个控制器,

[Route("api/[controller]")]
public class ResponsesController : Controller
{
    [HttpPost]
    public void Data([FromBody] MyModel value)
    {
        var temp = value;
    }
}

[JsonObject]
[Serializable]
public class MyModel
{
    public string Url { get; set; }
}

我正在使用 chrome 开发者控制台这样发布,

function post_to_url(path, params, method) {
    method = method || "post";

    var form = document.createElement("form");

    //Move the submit function to another variable
    //so that it doesn't get overwritten.
    form._submit_function_ = form.submit;

    form.setAttribute("Content-Type", "application/json;charset=utf-8");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
    }

    document.body.appendChild(form);
    form._submit_function_(); //Call the renamed function.
}
var j = {"Url":"hello"};
post_to_url("http://localhost:63984/api/responses", j );

我得到的错误是 415,但我不确定出了什么问题,我实际上想收到 myModel[]

【问题讨论】:

  • 原始 HTTP 是什么样的?这通常是由无效的 HTTP 标头引起的。
  • 我注意到的第一件事是,您必须指定路线,例如:[HttpGet("All")][HttpPost("All")],无论实际上取决于您期望的操作。您也可以使用此语法[HttpPost] [Route("All")] 两者都是有效语法
  • 你为什么不在这里使用 AJAX?

标签: javascript c# asp.net-web-api2 asp.net-core-2.0


【解决方案1】:

来自MDN

在来自 HTML 表单提交的 POST 请求中,请求的 Content-Type 由元素上的 enctype 属性指定。

您应该从您的post_to_url 中删除form.setAttribute("Content-Type", "application/json;charset=utf8")。如果您打算以这种方式提交数据,则可能必须将服务配置为接受 url 编码的表单数据。不过,对于这么简单的事情,它可能开箱即用。

【讨论】:

    【解决方案2】:

    415 表示“不支持的媒体”。在您的情况下,您将内容类型设置为 JSON,但您并没有真正发布 JSON,而是发布了一个带有 name="Url" 和 value="hello" 的隐藏字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      相关资源
      最近更新 更多