在客户端没有显示ASP.NET MVC HttpException消息 [英] ASP.NET MVC HttpException message not shown on client

查看:83
本文介绍了在客户端没有显示ASP.NET MVC HttpException消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建与asp.net的MVC,它返回纯JSON数据的REST风格的Web API。在我的客户,我使用Backbone.js的交流吧。

I'm building a RESTful web api with asp.net mvc, which returns pure json data. On my client, I'm using backbone.js to communicate to it.

我的问题是,我该如何捕捉JavaScript中的信息呢?对于如。如果一个用户没有权限删除或者根本没有的项目相匹配的ID?有人告诉我抛出HTTP错误,而不是定制的JSON。
所以,我的code将是:

My question is, how do I capture the message in javascript? For eg. What if a user has no permission to delete or there was no item matching the id? I've been told to throw http errors instead of custom 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);
    }

如何在我的JavaScript回调访问消息?回调将如下所示:

How do I access the message in my javascript callback? 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);
    }
});

现在有一个与401状态code一个警告。当您从服务器抛出401 HTTP异常,窗体身份验证模块拦截,并自动呈现登录页面和200.因此,错误处理程序不会为这个特殊的状态code执行替换401状态code

Now there is a caveat with 401 status code. 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.

这篇关于在客户端没有显示ASP.NET MVC HttpException消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆