在ASP.NET MVC 3中使用Ajax响应发送自定义错误页面

Mik*_*ynn 4 error-handling asp.net-mvc

为什么在发生错误时会使用下面的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>
Run Code Online (Sandbox Code Playgroud)

Web.Config中

 <customErrors defaultRedirect="Error" mode="On"></customErrors>
Run Code Online (Sandbox Code Playgroud)

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);
            }
        }


   }
Run Code Online (Sandbox Code Playgroud)

小智 5

如果有人还有这个问题,我发现了一个稍微清洁的解决方案:

if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
        //non-ajax exception handling code here
}
else
{
        filterContext.Result = new HttpStatusCodeResult(500);
        filterContext.ExceptionHandled = true;
}
Run Code Online (Sandbox Code Playgroud)