首页 > 解决方案 > 在 MVC 中将自定义错误页面添加到管理区域

问题描述

在我的网站中,有两个部分,
1. 任何用户(公共用户)都可以访问的页面。
2. 认证用户访问的管理区域。

为了向公共用户显示 404 错误,我创建了自定义页面并将以下部分添加到根 web.config

<customErrors mode="On">
      <error statusCode="404" redirect="~/Error/PageNotFound"/>
 </customErrors>


为了显示管理区域的自定义 404 错误,我在管理区域视图中创建了一个自定义页面,并将以下部分添加到管理区域文件夹中的 web.config 中。

<httpErrors errorMode="Custom" >
      <remove statusCode="404" />
      <error statusCode="404" path="~/Admin/AdminError/AdminError" responseMode="Redirect" />
    </httpErrors>


当我尝试创建 404 错误(通过键入无效的管理 url)时,应用程序在根文件夹中显示 404 页面。

我做错了什么,我该如何解决这个问题?

标签: asp.net-mvcasp.net-mvc-5custom-error-pagescustom-error-handling

解决方案


将区域添加到您的应用程序。右键单击您的项目,然后单击添加...区域。称它为管理员。实际上你只是在你的主 web.config 中设置它。

<system.web>
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/500.html">
  <error statusCode="404" redirect="~/404.html" />
  <error statusCode="500" redirect="~/500.html" />
</customErrors>
</system.web>

<location path="MyArea1">
<system.web>
  <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Areas/MyArea1/500.html">
    <error statusCode="404" redirect="~/Areas/MyArea1/404.html" />
    <error statusCode="500" redirect="~/Areas/MyArea1/500.html" />
  </customErrors>
</system.web>

然后处理 Global.asax 中的 Application_Error。

protected void Application_Error(object sender, EventArgs e)
    {

        string area = Request.FilePath.Split('/')[1];
        if (area.Equals("AreaName"))
        {
            Exception exception = Server.GetLastError();
            Response.Clear();
            HttpException httpException = exception as HttpException;
            Response.TrySkipIisCustomErrors = true;

            switch (httpException.GetHttpCode())
            {
                case 404:
                    Server.Transfer("~/Areas/AreaName/404.html");
                    break;
                case 500:
                default:
                    Server.Transfer("~/Areas/AreaName/500.html");
                    break;
            }
            Server.ClearError();
        }
    }

推荐阅读