gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:03:20 25 4
gpt4 key购买 nike

为什么自定义错误页面会在发生错误时与下面的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>

网页配置
 <customErrors defaultRedirect="Error" mode="On"></customErrors>

基础 Controller .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;
}

关于asp.net-mvc - 在 ASP.NET MVC 3 中使用 Ajax 响应发送自定义错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7114904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com