我正在尝试保护一个由jQuery ajax函数调用的控制器动作。
在我的动作方法中,我将代码放置在try-catch块中,因此我捕获了所有异常并返回带有异常消息的JSON结果。到这一点为止一切顺利。
问题出现在我在try-catch块之外抛出异常时,例如,如果异常在过滤器操作属性内引发。在这种情况下,我无法返回JSON结果,因为流会突然停止。
jQuery会在错误回调函数中捕获该异常。但是我唯一成功看到异常消息的地方是在xhr.responseText中,但它包含asp.net的整个“黄页”错误信息。
我使用的非常丑陋和hackish的解决方案是提取标题标签之间的文本。但我真的希望有更好的方法来做这件事!
在此情况下,您会怎么做?如何在不在动作方法内编写该逻辑的情况下保护您的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.");
}