【发布时间】:2011-05-05 15:00:04
【问题描述】:
我正在尝试保护使用 jQuery ajax 函数调用的控制器操作。
在我的操作方法中,代码被 try-catch 块包围,因此我捕获了所有异常并返回带有异常消息的 JSON 结果。到那时,一切都很好。
当我在 try-catch 块之外抛出异常时,问题就开始了,例如,如果在过滤器操作属性内引发异常。在这种情况下,我无法返回 JSON 结果,因为流程突然停止。
jQuery 在错误回调函数中捕获该异常。但我设法看到异常消息的唯一地方是 xhr.responseText,但它包含来自 asp.net 的整个“死亡黄页”错误。
我用来获取异常消息的非常丑陋和骇人听闻的解决方案是提取
在这种情况下你会怎么做?如果不在操作方法中编写该逻辑,您将如何保护您的 ajax 操作? 如何向用户显示由 jQuery ajax 调用的 ASP.NET MVC 控制器操作引发的未处理异常的消息?
jQuery Ajax 调用:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: url + "?id=" + id,
success: function(data) {
if(data.success){
alert('Success');
} else {
alert('Fail: ' + data.message);
},
error: function(xhr, status, err) {
// There has to be a better way to do this!!
var title = xhr.responseText.split("<title>")[1].split("</title>")[0];
alert(title);
}
});
控制器动作:
[MyAttribute]
public ActionResult MyAction(int id)
{
try
{
// Do something
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
catch (Exception exception)
{
return Json(new { success = false, message = exception.Message }, JsonRequestBehavior.AllowGet);
}
}
动作过滤器属性:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// This causes a 401 Unauthorized HTTP error.
throw new UnauthorizedAccessException("Access Denied.");
}
【问题讨论】:
标签: asp.net-mvc ajax asp.net-mvc-2 jquery