首页 > 解决方案 > 如何使 MVC 应用程序使用自定义错误页面

问题描述

我已在此处关注此帖子的答案,但在遇到 404 错误时,我无法让应用程序重定向到自定义页面。

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

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

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

filters.Add(new HandleErrorAttribute());我试过在 FilterConfig.cs 中注释掉

我尝试defaultRedirect在我的 web.config 文件中进行调整。

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

这是我的代码:

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");
    }
}

错误.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 还是它的位置?

标签: asp.netmodel-view-controllererror-handlingweb-config

解决方案


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

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

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


推荐阅读