【问题标题】:httpPost Not Found from Ajax request从 Ajax 请求中找不到 httpPost
【发布时间】:2018-02-07 23:37:09
【问题描述】:

我的 asp.net httpPost 无法通过 AJAX 请求工作。

我的控制器:

[Route("api/sendData")]
public class TestController : ApiController
{
    [HttpPost]
    public bool Post(PostData data)
    {

        return true;
    }
}

我的帖子数据:

public class PostData
{
    public int Id { get; set; }
}

我来自 html 文件的 AJAX 请求:

var data = {
        Id : 1
    };
    $.ajax(
        {
            url: "api/sendData",
            type: "POST",
            dataType: 'json',
            data: data,
            success: function (result) {
                console.debug(result);
                alert(result);
            },
            error: function (xhr, status, p3, p4) {
                console.debug(xhr);
                var err = "Error " + " " + status + " " + p3;
                if (xhr.responseText && xhr.responseText[0] == "{")
                    err = JSON.parse(xhr.responseText).message;
                alert(err);
            }
        });

我不知道为什么它返回 404 Not Found。有人知道我做错了什么吗?

谢谢

【问题讨论】:

  • 我的 ajax 有问题吗?

标签: jquery asp.net ajax http-post


【解决方案1】:

RouteAttribute 应该应用在动作方法名称而不是控制器类之上,以便动作方法变成这样:

public class TestController : ApiController
{
    [HttpPost]
    [Route("api/sendData")]
    public bool Post(PostData data)
    {
        return true;
    }
}

如果你想在控制器类级别使用属性路由,应该使用RoutePrefixAttribute

另外,如果你想在对象模型中传递属性,你需要使用JSON.stringify并设置contentType: "application/json",因为你想将JSON对象发送到action方法中:

<script>
    var data = { Id: 1, 
                 // other properties 
               };
    $.ajax({
        url: "api/sendData",
        type: "POST",
        contentType: "application/json",
        dataType: 'json',
        data: JSON.stringify(data),
        success: function (result) {
            console.debug(result);
            alert(result);
        },
        error: function (xhr, status, p3, p4) {
            // error handling here
        }
    });
</script>

【讨论】:

    猜你喜欢
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 2017-07-14
    相关资源
    最近更新 更多