Javascript 客户端上未显示ASP.NET MVC HttpException消息
我正在用asp.NETMVC构建一个RESTfulWebAPI,它返回纯json数据。在我的客户端上,我使用backbone.js与它通信 我的问题是,如何用javascript捕获消息?例如,如果用户没有删除权限,或者没有与id匹配的项目,该怎么办?我被告知抛出http错误,而不是自定义json。 所以我的代码是:Javascript 客户端上未显示ASP.NET MVC HttpException消息,javascript,asp.net,asp.net-mvc,Javascript,Asp.net,Asp.net Mvc,我正在用asp.NETMVC构建一个RESTfulWebAPI,它返回纯json数据。在我的客户端上,我使用backbone.js与它通信 我的问题是,如何用javascript捕获消息?例如,如果用户没有删除权限,或者没有与id匹配的项目,该怎么办?我被告知抛出http错误,而不是自定义json。 所以我的代码是: [HttpDelete] public ActionResult Index(int id) { if (id == 1)
[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
}
在从服务器返回的数据中,我根本看不到我抛出异常的消息。您应该在客户端上使用错误回调。只有在请求成功时才会触发成功回调:
$.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。因此,不会对这个特定的状态代码执行错误处理程序。我刚才在问题中回答了这个问题,但是如果您像这样使用HttpStatusCodeResult,您实际上可以得到该字符串:
$.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');
}
},
在控制器中:
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');
}
},
$.ajax:{
url:“@url.Action(“RequestsAdminAjax”,“Admin”)”,
类型:“POST”,
data:function(data){return JSON.stringify(data);},
contentType:“应用程序/json;字符集=utf-8”,
错误:函数(xhr、textStatus、errorshown){
调试器;
TogleAlert(“错误:无法加载数据。”,“警报危险”);
}
},
和errorshown
将包含“发生了不好的事情”
HTH.您好,如何访问抛出错误时传递的特定字符串,如:
“没有具有该ID的用户”
?errorhorn
中的数据是完整的错误html页面。@Lol coder,如果你想访问字符串和内容,你应该返回JSON对象,不要抛出任何异常。您应该选择两种方法中的哪一种:一种是完全RESTFul API,其中状态代码足够并允许您暗示错误消息,另一种是返回JSON对象。