自定义错误页面在活动服务器上不起作用
本文关键字:服务器 不起作用 活动 错误 自定义 | 更新日期: 2023-09-27 17:55:28
我已经在我的项目中实现了自定义错误功能,它在本地IIS上工作,但在实时服务器上不起作用。我已经使用 Global.asax 文件实现了此功能,并且我在 MVC 中的自定义错误控制器中调用了我的自定义错误操作方法。我已经在本地IIS上发布并运行,并且它运行良好,但是在实时服务器上。
我的 Global.asax.cs 文件
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
//do not register HandleErrorAttribute. use classic error handling mode
filters.Add(new HandleErrorAttribute());
}
protected void Application_Error(Object sender, EventArgs e)
{
LogException(Server.GetLastError());
CustomErrorsSection customErrorsSection = (CustomErrorsSection)ConfigurationManager.GetSection("system.web/customErrors");
string defaultRedirect = customErrorsSection.DefaultRedirect;
if (customErrorsSection.Mod e== CustomErrorsMode.On)
{
var ex = Server.GetLastError().GetBaseException();
Server.ClearError();
var routeData = new RouteData();
routeData.Values.Add("controller", "Common");
routeData.Values.Add("action", "CustomError");
if (ex is HttpException)
{
var httpException = (HttpException)ex;
var code = httpException.GetHttpCode();
routeData.Values.Add("status", code);
}
else
{
routeData.Values.Add("status", 500);
}
routeData.Values.Add("error", ex);
IController errorController = new Test.Controllers.CommonController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
}
我的自定义错误控制器及其操作方法
public ActionResult CustomError(int status, Exception error)
{
var model = new CustomErrorModel();
model.Code = status;
model.Description = Convert.ToString(error);
Response.StatusCode = status;
return View(model);
}
那我该怎么办?
我遇到了这个问题,实时IIS服务器上的错误没有显示自定义错误页面(返回正确的HttpStatusCodes),但它在本地IIS上工作(使用默认网站的本地主机地址 - 不是卡西尼)。它们应该与我认为完全相同 - 无论如何,这个 web.config 设置修复了它。
<configuration>
<system.webServer>
<httpErrors existingResponse="PassThrough"></httpErrors>
</system.webServer>
</configuration>
请注意,我的设置在global.asax中使用Application_Error,并且只使用其他web.config设置:
<customErrors mode="On">
<!-- There is custom handling of errors in Global.asax -->
</customErrors>
2 种方法
路由方法
// We couldn't find a route to handle the request. Show the 404 page.
routes.MapRoute("Error", "{*url}", new { controller = "Error", action = "CustomError" } );
或
Web.config 中的自定义错误处理程序:
<customErrors mode="On" >
<error statusCode="404" redirect="~/CatchallController/CustomError" />
</customErrors>
没有路由匹配引发的条件是 404。这样,您可以将所有不匹配的内容定向到您的~/CatchallController/CustomError