當發生錯誤時,爲什麼自定義錯誤頁面將與下面的ajax響應一起發送?在ASP.NET MVC 3中使用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);
}
}
}
雖然dsomuah的代碼可以很容易地進入你的控制器基類,因爲很多項目已經實現了由於種種原因,它很高興看到這裏列出此方法。 +1 – shannon