这个问题在这里已经有了答案:
Routing for custom ASP.NET MVC 404 Error page
(10 个回答)
6年前关闭。
有人可以解释一下如何在我的项目中添加自定义 404 和 500 错误吗?我尝试将其添加到 Web.config:
<customErrors mode="On">
<error code="404" path="404.html" />
<error code="500" path="500.html" />
</customErrors>
最佳答案
如果来自 Controller 的操作方法抛出异常,则调用 OnException 方法。与 HandleErrorAttribute 不同,它还会捕获 404 和其他 HTTP 错误代码,并且不需要打开 customErrors。
它是通过重写 Controller 中的 OnException 方法来实现的:
protected override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
// Redirect on error:
filterContext.Result = RedirectToAction("Index", "Error");
// OR set the result without redirection:
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Error/Index.cshtml"
};
}
使用 filterContext.ExceptionHandled 属性,您可以检查是否在早期阶段处理了异常(例如 HandleErrorAttribute):
if (filterContext.ExceptionHandled)
返回;
互联网上的许多解决方案建议创建一个基本 Controller 类并在一个地方实现 OnException 方法以获取全局错误处理程序。
但是,这并不理想,因为 OnException 方法在其范围内几乎与 HandleErrorAttribute 一样有限。您最终将至少在另一个地方复制您的工作。
关于c# - 自定义错误 MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37150350/