2011-07-10 68 views
0

我正在用asp.net mvc构建一个REST风格的web api,它会返回纯json数据。在我的客户端,我使用backbone.js与之通信。ASP.NET MVC HttpException消息未在客户端上显示

我的问题是,我如何捕捉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 
} 

我没有看到消息,我从服务器返回的数据中发现任何异常情况。

回答

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异常时,表单认证模块拦截它并自动呈现LogIn页面并用200替换401状态码。所以错误处理程序将不会被执行用于这个特定的状态码。

+0

嗨,我如何访问一个特定的字符串,如:''没有该用户名的用户''',这是抛出错误时通过? 'errorThrown'中的数据是完整的错误html页面。 –

+0

@Lol编码器,如果你想访问字符串和东西,你应该返回JSON对象,而不是抛出任何异常。您应该选择您想要的两种:完全RESTFul API,其中状态码足以让您暗示错误消息或返回JSON对象。 –

0

我只是在我的问题What is the point of HttpException in ASP.NET MVC回答了这个,但如果你使用HttpStatusCodeResult这样其实你可以得到该字符串:

在你的控制器:

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

,您可以访问“坏事发生”使用,比如jQuery的$。阿贾克斯()是这样的:

    $.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。

相关问题