【问题标题】:Custom Errors MVC 5 [duplicate]自定义错误 MVC 5 [重复]
【发布时间】:2016-09-06 03:06:33
【问题描述】:

谁能解释我如何在我的项目中添加自定义 404 和 500 错误?我尝试将其添加到 Web.config:

<customErrors mode="On">
    <error code="404" path="404.html" />
    <error code="500" path="500.html" />
</customErrors>

【问题讨论】:

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


    【解决方案1】:

    如果来自控制器的操作方法抛出异常,则会调用 OnException 方法。与 HandleErrorAttribute 不同,它还会捕获 404 和其他 HTTP 错误代码,并且不需要打开 customErrors。

    它是通过重写控制器中的 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) 返回; 网上很多解决方案都建议创建一个基础控制器类并在一个地方实现 OnException 方法来获取全局错误处理程序。

    但是,这并不理想,因为 OnException 方法在其范围内几乎与 HandleErrorAttribute 一样有限。你最终会在至少一个地方重复你的工作。

    【讨论】:

      【解决方案2】:

      这是我最近读到的最好的文章,让你知道你将要进入的快乐http://benfoster.io/blog/aspnet-mvc-custom-error-pages 我的 customErrors 元素看起来像这样。

       <customErrors mode="Off" redirectMode="ResponseRewrite">
        <error statusCode="404" redirect="/404.aspx" />
        <error statusCode="500" redirect="/500.aspx"/>
      </customErrors>
      

      【讨论】:

        猜你喜欢
        • 2014-06-27
        • 2014-11-09
        • 1970-01-01
        • 2015-11-14
        • 2015-07-28
        • 2017-09-29
        • 1970-01-01
        • 1970-01-01
        • 2013-01-10
        相关资源
        最近更新 更多