我有一个相对未受影响的 MVC4 项目,在我的 Web.Release.config 中包含以下内容:
<system.web>
<customErrors mode="On" defaultRedirect="~/Error">
<error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
</system.web>
但它不起作用 - 在 Release模式下我收到正常的错误页面。
如果我将该代码放入我的 Web.Config 中,它就会按预期工作。我只希望在发布时应用此功能。
我也在 web.release.config 中尝试过:
<system.web>
<customErrors mode="On" defaultRedirect="~/Error" xdt:Transform="Replace">
<error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>
<compilation xdt:Transform="RemoveAttributes(debug)" />
</system.web>
没有效果。
为什么会发生这种情况?
更新:如果我在 global.asax 中使用以下内容:
void Application_Error(object sender, EventArgs e)
{
#if DEBUG
#else
Response.Redirect("/Error");
#endif
return;
}
我得到了想要的行为。我觉得我应该只能使用 web.config 设置...所以我想将其保持打开状态。
最佳答案
问题是你没有发布。据我所知,web.release.config 文件仅在发布期间进行转换。如果您只是在本地构建并运行该文件,则不会使用该文件。
此外,在您的 Application_Error
中,您应该获得错误的状态代码。类似的东西
var exception = Server.GetLastError();
var httpException = exception as HttpException;
if (httpException != null)
{
if (httpException.GetHttpCode() == 404)
RedirectToMyNotFoundPage();
}
否则你基本上只会处理所有错误,这可能是也可能不是你想要做的。
如果你想处理 MvcErrors,并获取发生异常的 Controller /操作,你应该查看过滤器。
如果您想要的话,这里有一篇关于错误过滤的好文章。
关于asp.net - 使用 MVC4 自定义错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19191950/