【问题标题】:AJAX Delete action going to the wrong methodAJAX删除动作去错了方法
【发布时间】:2014-03-20 14:41:15
【问题描述】:

我正在尝试通过AJAX 调用从数据库中删除一条记录,如下所示:

$.ajax({
    type: 'POST',
    url: '/api/Person/DeletePerson',
    data: { personId: personId },
    contentType: 'application/json',
    success: function (data) {
        if (data != null) {

        }
    },
    error: function (err, data) {
        alert("Error " + err.responseText);
    }
});

这是它应该输入的方法:

public void DeletePerson(int personId)
{
var t = 0; // i'm breaking the debugger right here, never gets hit.
}

但是反而一直输入这个方法:

public HttpResponseMessage PostPerson(dynamic person)
{
    HttpResponseMessage response;

    if (User.Identity.GetUserId() == null)
    {
        response = Request.CreateResponse(HttpStatusCode.Forbidden, "Please log in."); 
    }

    return response;
}

这两种方法都驻留在 WebApi Controller 中。

AJAX Type: delete 不受支持。如果我改用它,我会收到此消息:

The requested resource does not support http method 'delete'

我该如何完成这项工作?

编辑

public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

【问题讨论】:

    标签: jquery ajax asp.net-web-api asp.net-mvc-5


    【解决方案1】:

    调用 Delete 方法(因为这是一个 rest 实现)使用 DELETE 动词调用 /api/Person/ URL。

    $.ajax({
        type: 'DELETE',
        url: '/api/Person',
        data: { personId: personId },
        contentType: 'application/json',
        success: function (data) {
            if (data != null) {
    
            }
        },
        error: function (err, data) {
            alert("Error " + err.responseText);
        }
    });
    

    否则你需要更新动作以接受删除动词

    [HttpDelete]
    public void DeletePerson(int personId)
    {
    var t = 0; // i'm breaking the debugger right here, never gets hit.
    }
    

    如果您想让控制器从 JSON 有效负载而不是请求 URL 中查找 id,请改写如下。

    public void DeletePerson([FromBody]int personId)
    {
        var t = 0; // i'm breaking the debugger right here, never gets hit.
    }
    

    【讨论】:

    • 在我的问题中,我说delete 作为type 不适用于我收到的错误消息。但这是我最初的尝试,我放弃了尝试。
    • 你能用你正在使用的 webapi 路由更新你的问题吗?也许是导致这种行为的 personId/person 参数?
    • 当然,它已更新。但我没有使用任何自定义路由,只是标准路由。
    • 请求URL选项是怎么做的?如果没有[frombody],我需要进行哪些调整才能使其正常工作?
    • 对 /api/Person/1 的请求,其中 1 是要删除的 id。如果路由中的参数名称与方法签名中的参数名称相同,即personId,这将起作用。
    猜你喜欢
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2014-06-19
    • 2019-02-27
    相关资源
    最近更新 更多