c# - 自定义错误 MVC 5

标签 c# asp.net-mvc error-handling http-status-code-404 http-status-code-500

这个问题在这里已经有了答案:





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/

相关文章:

c# - C# 可以像 Java 一样简单地打印集合值吗?

asp.net-mvc - 具有服务层和存储库层的ASP.NET MVC,应在哪里定义接口(interface)?

configuration - 为什么 PHP 5.2.14 不显示任何错误(即使是从命令行)?

iOS swift : Parse Invalid Session Token Error

c# - DateTimeFormatInfo.MonthDayPattern 在 Windows Server 2012 中已更改 - 如何将其恢复?

c# - UnitOfWork & Generic Repository,带有自定义存储库的 SOLID 原则

c# - Linux 上的单声道 : mkbundle does not find shared libraries

c# - 带有 ApplicationPath 的 ASP.NET MVC Action

c# - 同时执行 Javascript 和 Controller ActionResult

bash - Bash脚本,错误输出重定向