asp.net - 如何使 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 还是它的位置?
解决方案
一切都设置得很完美。唯一的问题是我正在修改 Web.Debug.config 而不是 Web.config 文件。将配置更改移动到父 Web.config 文件后,我的错误页面开始显示。
此外,这:defaultRedirect="~/Views/Error/Error"
作为默认重定向对我不起作用。必须是控制器动作而不是路径。为什么路径对其他人有用,我还不知道,因为这整个空间对我来说是新的。
希望有一天这对某人有所帮助。
推荐阅读
- outlook - Outlook:使用模板全部回复多封电子邮件
- dolphindb - DolphinDB如何在状态变化时自动将新状态写入keyedTable
- freeswitch - 将潮流 FXO 网关与 fusionPBX 云连接
- javascript - 条纹支付表单未在 React 中显示
- javascript - 如何在项目中移动 axios 实例
- python-3.x - 类型错误:%x 格式:需要一个整数,而不是字节
- python - 如何拆分Python列表中的项目?
- shopify - Shopify Admin Api /checkouts -“错误”:“未找到”
- vue.js - 如何将 UI 框架 Quasar 安装到现有的 Vue JS 项目中
- javascript - 汇总包无法映射别名导入