【问题标题】:ASP.NET MVC HttpException message not shown on clientASP.NET MVC HttpException 消息未显示在客户端
【发布时间】:2011-07-10 07:56:34
【问题描述】:

我正在使用 asp.net mvc 构建一个 RESTful web api,它返回纯 json 数据。在我的客户端上,我使用backbone.js 与之通信。

我的问题是,如何在 javascript 中捕获消息?例如。如果用户无权删除或没有与 id 匹配的项目怎么办?我被告知要抛出 http 错误而不是自定义 json。 所以我的代码是:

    [HttpDelete]
    public ActionResult Index(int id)
    {
        if (id == 1)
        {
            throw new HttpException(404, "No user with that ID");
        }
        else if (id == 2)
        {
            throw new HttpException(401, "You have no authorization to delete this user");
        }
        return Json(true);
    }

如何访问我的 javascript 回调中的消息?回调看起来像:

function (model, response) {
   alert("failed");
   //response.responseText would contain the html you would see for asp.net
}

在从服务器返回的数据中,我在任何地方都没有看到我在异常中抛出的消息。

【问题讨论】:

    标签: javascript asp.net asp.net-mvc


    【解决方案1】:

    您应该在客户端使用错误回调。只有请求成功才会触发成功回调:

    $.ajax({
        url: '/home/index',
        type: 'DELETE',
        data: { id: 1 },
        success: function (result) {
            alert('success'); // result will always be true here
        },
        error: function (jqXHR, textStatus, errorThrown) {
            var statusCode = jqXHR.status; // will equal to 404
            alert(statusCode);
        }
    });
    

    现在有一个 401 状态代码的警告。当您从服务器抛出 401 HTTP 异常时,表单身份验证模块会拦截它并自动呈现登录页面并将 401 状态代码替换为 200。因此不会针对此特定状态代码执行错误处理程序。

    【讨论】:

    • 嗨,我如何访问一个特定的字符串,例如:"No user with that ID",它是在抛出错误时传递的? errorThrown中的数据是完整的错误html页面。
    • @Lol 编码器,如果你想访问字符串和东西,你应该返回 JSON 对象而不抛出任何异常。您应该选择您想要的两者中的哪一个:或者是完全 RESTFul API,其中状态代码足够,并允许您暗示错误消息或返回 JSON 对象。
    【解决方案2】:

    我刚刚在我的问题What is the point of HttpException in ASP.NET MVC 中回答了这个问题,但是如果您像这样使用 HttpStatusCodeResult,您实际上可以获得该字符串:

    在您的控制器中:

    return new HttpStatusCodeResult(500,"Something bad happened")
    

    您可以像这样使用 jQuery $.ajax() 访问“发生了一些事情”:

                        $.ajax: {
                            url: "@Url.Action("RequestsAdminAjax", "Admin")",
                            type: "POST",
                            data: function(data) { return JSON.stringify(data); },
                            contentType: "application/json; charset=utf-8",
                            error: function (xhr, textStatus,errorThrown) {
                                debugger;
                                toggleAlert('<strong>Error: </strong>Unable to load data.', 'alert alert-danger');
                            }
                        },
    

    errorThrown 将包含“发生了不好的事情”。

    HTH。

    【讨论】:

      猜你喜欢
      • 2012-08-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多