简体   繁体   English

ASP.NET MVC HttpException 消息未显示在客户端

[英]ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with asp.net mvc, which returns pure json data.我正在使用 asp.net mvc 构建一个 RESTful web api,它返回纯 Z466DEEC76ECDF54D54Z38 数据。 On my client, I'm using backbone.js to communicate to it.在我的客户端上,我使用 backbone.js 与之通信。

My question is, how do I capture the message in javascript?我的问题是,如何捕获 javascript 中的消息? For eg.例如。 What if a user has no permission to delete or there was no item matching the id?如果用户无权删除或没有与 id 匹配的项目怎么办? I've been told to throw http errors instead of custom json.我被告知要抛出 http 错误,而不是自定义 json。 So my code would be:所以我的代码是:

    [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);
    }

How do I access the message in my javascript callback?如何访问我的 javascript 回调中的消息? The callback would look like:回调看起来像:

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

I do not see message i threw in the exception anywhere at all in the data that was returned from the server.在从服务器返回的数据中,我没有看到我在任何地方抛出异常的消息。

You should use the error callback on the client.您应该在客户端上使用错误回调。 The success callback is triggered only when the request succeeds:只有在请求成功时才会触发成功回调:

$.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);
    }
});

Now there is a caveat with 401 status code.现在有一个 401 状态码的警告。 When you throw 401 HTTP exception from the server, the forms authentication module intercepts it and automatically renders the LogIn page and replaces the 401 status code with 200. So the error handler will not be executed for this particular status code.当您从服务器抛出 401 HTTP 异常时,forms 身份验证模块会拦截它并自动呈现登录页面并将 401 状态代码替换为 200。因此不会针对此特定状态代码执行错误处理程序。

I just answered this in my question What is the point of HttpException in ASP.NET MVC , but you can actually get that string if you use the HttpStatusCodeResult like this:我刚刚在我的问题What is the point of HttpException in ASP.NET MVC 中回答了这个问题,但是如果您像这样使用 HttpStatusCodeResult ,您实际上可以获得该字符串:

In your controller:在您的 controller 中:

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

And you can access "Something bad happened" using, say, jQuery $.ajax() like this:您可以使用 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');
                        }
                    },

and errorThrown will contain "Something bad happened".并且errorThrown将包含“发生了不好的事情”。

HTH. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM