加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 在ASP.NET MVC 3中使用Ajax响应发送的自定义错误

发布时间:2020-12-16 06:29:51 所属栏目:asp.Net 来源:网络整理
导读:为什么在发生错误时会使用下面的ajax响应发送自定义错误页面? 响应 {"Errors":["An error has occurred and we have been notified. We are sorry for the inconvenience."]}!DOCTYPE htmlhtmlhead meta charset="utf-8" / titleError/title Web.Config中 c
为什么在发生错误时会使用下面的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);
            }
        }


   }

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读