从MVC HttpPost向jQuery抛出错误

5

我有一个控制器中的方法如下:

[HttpPost]
public void UnfavoriteEvent(int id)
{
    try
    {
        var rows = _connection.Execute("DELETE UserEvent WHERE UserID = (SELECT up.UserID FROM UserProfile up WHERE up.UserName = @UserName) AND EventID = @EventID",
            new { EventID = id, UserName = User.Identity.Name });
        if (rows != 1)
        {
            Response.StatusCode = 500;
            Response.Status = "There was an unknown error updating the database.";
            //throw new HttpException(500, "There was an unknown error updating the database.");
        }
    }
    catch (Exception ex)
    {
        Response.StatusCode = 500;
        Response.Status = ex.Message;
        //throw new HttpException(500, ex.Message);
    }
}

正如您所见,我已经尝试了几种不同的方法来抛出此错误。在JavaScript代码中,我有以下块来调用此方法:

var jqXHR;
if (isFavorite) {
    jqXHR = $.ajax({
        type: 'POST',
        url: '/Account/UnfavoriteEvent',
        data: { id: $("#EventID").val() }
    });
}
else {
    jqXHR = $.ajax({
        type: 'POST',
        url: '/Account/FavoriteEvent',
        data: { id: $("#EventID").val() }
    });
}

jqXHR.error = function (data) {
    $("#ajaxErrorMessage").val(data);
    $("#ajaxError").toggle(2000);
};

现在,我想要做的是将发生的错误抛回到jqXHR.error函数中,以便我可以正确处理它。
目前未注释的代码会抛出异常,说明我放置在Status中的文本不被允许,而已注释的代码实际上返回标准错误页面作为响应(这并不奇怪)。
所以,我有几个问题:
  1. 如何正确地抛出错误?
  2. Response.Status属性是什么作用?
谢谢大家!

由于您正在捕获通用异常,因此不应将特定消息发送回客户端。这可能会成为有关您的应用程序的敏感信息。如果捕获自定义域异常并且您控制消息,则可以将它们发送到客户端,但对于通用异常,应发送通用消息。 - BZink
@BZink,非常好的观点。谢谢。 - Mike Perrenoud
2个回答

3
您可以从 JavaScript 中获取响应状态,只需执行以下操作:
$.ajax({
    type: 'POST',
    url: '/Account/UnfavoriteEvent',
    data: { id: $("#EventID").val() },
    success: function(data, textStatus, jqXHR) {
        // jqXHR.status contains the Response.Status set on the server
    },
    error: function(jqXHR, textStatus, errorThrown) {
        // jqXHR.status contains the Response.Status set on the server
    }});

如您所见,您必须将error函数传递给ajax函数... 在您的示例中,您将该函数设置为jqXHRerror属性,但根本没有任何效果。 jQuery - Ajax Events文档称错误字符串将出现在errorThrown参数中。 不要使用Response 相反,您应该返回HttpStatusCodeResult:
[HttpPost]
public void UnfavoriteEvent(int id)
{
    try
    {
        var rows = _connection.Execute("DELETE UserEvent WHERE UserID = (SELECT up.UserID FROM UserProfile up WHERE up.UserName = @UserName) AND EventID = @EventID",
            new { EventID = id, UserName = User.Identity.Name });
        if (rows != 1)
        {
            return new HttpStatusCodeResult(500, "There was an unknown error updating the database.");
        }
    }
    catch (Exception ex)
    {
        return new HttpStatusCodeResult(500, ex.Message);
    }
}

那绝对让我进入了JavaScript中的错误方法,所以谢谢!但是我想要的错误字符串不在Response.Status中。我在服务器端做错了什么,如何将这个简单的消息传递给客户端? - Mike Perrenoud

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接