asp.net-mvc - 在 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 页面。
我做错了什么,我该如何解决这个问题?
解决方案
将区域添加到您的应用程序。右键单击您的项目,然后单击添加...区域。称它为管理员。实际上你只是在你的主 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();
}
}
推荐阅读
- json - 在 Go 中解析具有兄弟动态键和静态键的 JSON
- c++ - 正则表达式 - 在单独的捕获组中捕获每个参数:[cmd arg1 arg2 arg3...]
- google-cloud-platform - Colab / Google Cloud SDK - 本地运行时总是“忙” - 无法重新启动
- javascript - 如何确保当您单击其中一个箭头时,您会转到下一部分或上一部分?
- python - 在 PyQt5(Python)中将小部件(QCheckBox)添加到 QFileDialog 不起作用
- c# - 为什么VS2019还在把嵌入的资源复制到输出文件夹?
- javascript - 即使在配额扩展获得批准后,Spotify API 也不会向人们提供访问权限
- html - 如何在同一行中有一个列表、一个图像和一个 h1(但对齐方式不同)
- c# - 如何将excel中的表格放入C#中的可滚动项目列表中?
- python - pytest,是否可以在 pytest_generate_tests 中获取其他夹具的值?