【问题标题】:Getting "Method not allowed" error after handling a POST request处理 POST 请求后出现“方法不允许”错误
【发布时间】:2019-01-22 17:40:10
【问题描述】:

我遇到了主题所说的问题。我对这些东西很陌生,我什至不知道在哪里寻找那个问题。这是我的post方法:

public class Point
{
    public string x { get; set; }
    public string y { get; set; }
}

[HttpPost]
public IHttpActionResult Post([FromBody] Point point)
{
    // do stuff
    return StatusCode(HttpStatusCode.OK);
}

这是我的 ajax 请求:

var x = $('#input1').val();
var y = $('#input2').val();

$("#btnUpload").click(function () {
    $.ajax({
        type: "POST",
        url: "api/images",
        data: { x: x, y: y },
        success: function (result) { alert(result) },
        error: function (err) { alert(err.statusText) }
    });
});

我是不是忘记了什么?

编辑:我的控制器:

[RoutePrefix("api/images")]
public class ImagesController : ApiController
{
    private Bitmap CreateBoard()
    {
        // some stuff I need
    }

    [HttpPost]
    public IHttpActionResult Post([FromBody] Point point)
    {
        // do stuff
        return StatusCode(HttpStatusCode.OK);
    }

    [Route("")]
    [HttpGet]
    public List<int> Get()
    {
        // do other stuff
    }

    [Route("{id}")]
    [HttpGet]
    public HttpResponseMessage Get(int id)
    {
        // do other other stuff
    }
}

GET 工作正常。

【问题讨论】:

  • 你没有从Controller继承任何东西。
  • 您的Post 方法在哪个控制器中?路线是什么?
  • @maccettura 已编辑
  • @KirkLarkin 现在无论我在输入文本框中输入什么内容,我都会在 Point 参数中得到两个空值
  • 好的,我明白了,“contentType: 'application/json'” 它有帮助,你说的第二件事.. 我不知道它是怎么发生的:D

标签: c# ajax asp.net-web-api


【解决方案1】:

您的网址应为api/images/postRoutePrefix 是“api/images”,因此您缺少方法的名称。

【讨论】:

    猜你喜欢
    • 2013-10-10
    • 2021-09-21
    • 2018-05-24
    • 2020-01-15
    • 1970-01-01
    • 2017-11-03
    • 2014-01-08
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多