我正在用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
}
我没有看到消息,我从服务器返回的数据中发现任何异常情况。
嗨,我如何访问一个特定的字符串,如:''没有该用户名的用户''',这是抛出错误时通过? 'errorThrown'中的数据是完整的错误html页面。 –
@Lol编码器,如果你想访问字符串和东西,你应该返回JSON对象,而不是抛出任何异常。您应该选择您想要的两种:完全RESTFul API,其中状态码足以让您暗示错误消息或返回JSON对象。 –