我有一些类似于这样的jQuery代码:
$.ajax({
type: "POST",
url: "/Customer/CancelSubscription/<%= Model.Customer.Id %>",
contentType: "application/json",
success: refreshTransactions,
error: function(xhr, ajaxOptions, thrownError) {
alert("Failed to cancel subscription! Message:" + xhr.statusText);
}
});
如果调用的操作引发异常,最终将被 Global.asax 中的 Application_Error 捕获,我有一些类似以下代码的处理:var ex = Server.GetLastError();
if (Request.ContentType.Contains("application/json"))
{
Response.StatusCode = 500;
Response.StatusDescription = ex.Message;
Response.TrySkipIisCustomErrors = true;
}
else
{
// some other way of handling errors ...
}
当我执行进行帖子的脚本时,Request.ContentType总是空字符串,因此不会触发第一个if块。在ajax的"contentType"中是否应该放置其他值?或者有没有其他方法告诉asp.net内容类型应该是"application/json"?澄清: 我尝试实现的目标是将异常消息传递回ajax错误事件。目前,即使绕过了IF块,错误事件也会正确地抛出警报框,但消息为“未找到”。
正如您所看到的,我正在尝试将exeception消息设置为Response.StatusDescription,我相信ajax错误中的xhr.statusText被设置为该值。