我的问题是关于 Pure.Kromes 对这篇文章的回答。我尝试使用他的方法实现我的页面的自定义错误消息,但有些问题我无法完全解释。
a) 当我通过输入无效 URL(例如 localhost:3001/NonexistantPage)引发 404 错误时,它默认为我的错误控制器的 ServerError() 操作,即使它应该转到 NotFound()。这是我的错误控制器:
公共类 ErrorController : 控制器 { 公共 ActionResult NotFound() { Response.TrySkipIisCustomErrors = true; Response.StatusCode = (int)HttpStatusCode.NotFound; var viewModel = new ErrorViewModel() { ServerException = Server.GetLastError(), HTTPStatusCode = Response.StatusCode }; 返回视图(视图模型); } 公共 ActionResult ServerError() { Response.TrySkipIisCustomErrors = true; Response.StatusCode = (int)HttpStatusCode.InternalServerError; var viewModel = new ErrorViewModel() { ServerException = Server.GetLastError(), HTTPStatusCode = Response.StatusCode }; 返回视图(视图模型); } }
我在 Global.asax.cs 中的错误路线:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
name: "Error - 404",
url: "NotFound",
defaults: new { controller = "Error", action = "NotFound" }
);
routes.MapRoute(
name: "Error - 500",
url: "ServerError",
defaults: new { controller = "Error", action = "ServerError" }
);
还有我的 web.config 设置:
<system.web>
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="/ServerError">
<error statusCode="404" redirect="/NotFound" />
</customErrors>
...
</system.web>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" path="/NotFound" responseMode="ExecuteURL" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="500" path="/ServerError" responseMode="ExecuteURL" />
</httpErrors>
...
错误视图位于 /Views/Error/ 作为 NotFound.cshtml 和 ServerError.cshtml。
b) 一件有趣的事情是,当发生服务器错误时,它实际上会显示我定义的服务器错误视图,但它也会输出默认错误消息,并指出找不到错误页面。
您对我如何解决这两个问题有什么建议吗?我真的很喜欢 Pure.Kromes 实现这些错误消息的方法,但如果有更好的方法来实现这一点,请毫不犹豫地告诉我。
谢谢!
**编辑:** 我可以通过访问 /Error/NotFound 或 Error/ServerError 通过 ErrorController 直接导航到我的视图。
视图本身只包含一些文本,没有标记或任何东西。
正如我所说,它实际上以某种方式工作,而不是我想要的工作方式。web.config 中的重定向似乎存在问题,但我无法弄清楚。