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

4
当发生错误时,为什么会将自定义错误页面与以下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);
            }
        }


   }
3个回答

5

如果还有人遇到这个问题,我发现有一个稍微更加简洁的解决方案:

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

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

尽管dsomuah的代码可以轻松地放入您的控制器基类中,因为许多项目已经出于各种原因实现了这一点,但在这里列出这种方法还是很好的。+1 - shannon

0

我加了 response.End(); 然后它就能用了。有更好的方法吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接