如何让 MVC 应用程序使用自定义错误页面

How to make MVC app use custom error page

我已按照 this post here 上的答案进行操作,但遇到 404 错误时无法让应用重定向到自定义页面。

当我访问 localhost:12345/error/NotFound 时,错误页面显示正常。所以查看 link 的控制器就在那里。

我设置了一个带有无效控制器名称的 <a> 标签来触发错误页面。单击 link 后,我将转到浏览器的默认错误页面,而不是我的自定义页面。

我试过将 <httpErrors existingResponse="PassThrough" /> 添加到 <system.webServer>

我试过在FilterConfig.cs

中注释掉filters.Add(new HandleErrorAttribute());

我已经尝试在我的 web.config 文件中调整 defaultRedirect

对我来说没有任何效果,而且我找不到任何好的直接文档。似乎人们有不同的方法和不同的解决方案为他们工作,而不是为其他人工作。只是让我想知道...

这是我的代码:

Web.Debug.config:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <system.web>
    <customErrors mode="On" defaultRedirect="~/Views/Error/Error">
      <error redirect="~/Error/NotFound" statusCode="404" />
    </customErrors>
  </system.web>
</configuration>

错误控制器:

public class ErrorController : Controller
{
    [AllowAnonymous]
    public PartialViewResult Error()
    {
        return PartialView("Error");
    }

    [AllowAnonymous]
    public PartialViewResult NotFound()
    {
        Response.StatusCode = 404;
        return PartialView("Error");
    }
}

Error.cshtml:

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="list-header clearfix">
    <span>Error</span>
</div>

<div class="list-sfs-holder">
    <div class="alert alert-error">
        An unexpected error has occurred. Please contact the system administrator.
    </div>
    @{
        if (Model != null && HttpContext.Current.IsDebuggingEnabled)
        {
            <div>
                <p>
                    <b>Exception:</b> @Model.Exception.Message<br />
                    <b></b> @Model.ControllerName<br />
                    <b></b> @Model.ActionName
                </p>
                <div style="overflow: scroll">
                    <pre>
                        @Model.Exception.StackTrace
                    </pre>
                </div>
            </div>
        }
    }
</div>

Error.cshtml的位置:

我做错了什么吗?我还需要处理其他设置吗?我的重定向路径应该指向 error.cshtml 还是它的位置?

一切都设置得很完美。唯一的问题是 我正在修改 Web.Debug.config 而不是 Web.config 文件 。一旦我将我的配置更改移动到父 Web.config 文件,我的错误页面开始出现。

此外,这个:defaultRedirect="~/Views/Error/Error" 作为默认重定向对我不起作用。必须是控制器动作而不是路径。为什么路径对其他人有用,我还不知道,因为整个 space 对我来说是新的。

希望有一天这对某人有所帮助。