为什么在发生错误时会使用下面的ajax响应发送自定义错误页面?
响应
{"Errors":["An error has occurred and we have been notified. We are sorry for the inconvenience."]}<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Error</title>
的Web.Config
<customErrors defaultRedirect="Error" mode="On"></customErrors>
BaseController.cs
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var response = filterContext.HttpContext.Response;
var validatorModel = new ValidatorModel();
if (filterContext.Exception is AriesException && !((AriesException)filterContext.Exception).Visible && filterContext.HttpContext.IsCustomErrorEnabled)
{
validatorModel.Errors.Add(this.Resource("UnknownError"));
}
else
{
validatorModel.Errors.Add(filterContext.Exception.Message);
}
response.Clear();
response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
response.Write(validatorModel.ToJson());
response.ContentType = "application/json";
response.TrySkipIisCustomErrors = true;
filterContext.ExceptionHandled = true;
System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
}
else if (filterContext.HttpContext.IsCustomErrorEnabled)
{
filterContext.ExceptionHandled = true;
}
if(filterContext.ExceptionHandled)
{
SiteLogger.Write(filterContext.Exception);
}
}
}
答案 0 :(得分:5)
如果有人仍有这个问题,我找到了一个稍微清洁的解决方案:
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
//non-ajax exception handling code here
}
else
{
filterContext.Result = new HttpStatusCodeResult(500);
filterContext.ExceptionHandled = true;
}
答案 1 :(得分:2)
dsomuah的解决方案很不错,但必须添加到为Ajax请求提供服务的每个控制器中。我们通过全局注册以下操作过滤器更进了一步:
public class HandleAjaxErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.HttpContext.Response.StatusDescription = filterContext.Exception.Message;
}
}
}
答案 2 :(得分:0)
我添加了response.End();它起作用了。还有更好的方法吗?