Application_Error Global.asax 中的事件在 IIS7 中未触发,但在 IIS6 中运行良好

Application_Error event in Global.asax not firing in IIS7, but works fine in IIS6

去年,我们将 Web 应用程序移至新服务器。以下是移动前的 system/application 配置规范:

以下是迁移到新服务器后的规格:

问题是,在搬家环境发生剧烈变化后,Global.asax中的Application_Error事件不再像以前那样触发了。我遇到过很多关于此的问题(请参阅此问题的末尾),但 none 的解决方案似乎有效。它们也很老了,所以我认为 SE 应该就此主题提供一些更新的答案。

我想做的事情:

如果抛出特定异常,我想导航到特定错误页面。否则,按照我的 web.config 中的定义继续 error.aspx。自移动以来,我没有对 web.config 或代码进行任何更改。这是 Application_Error 事件:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

    If TypeOf (Server.GetLastError) Is System.Web.HttpRequestValidationException Then
        NavigateToErrorPage("Display special error message here")
    End If

End Sub

customErrors 在 web.config:

<customErrors mode="RemoteOnly" defaultRedirect="error.aspx" />

那么我需要做什么才能使我的应用程序在 IIS 7.5 中的行为与在 IIS 6 中的行为相同?

编辑:我会注意到 Application_Error 事件在 运行 我的应用程序在本地主机下本地触发时触发。

我发现的其他无法在此处帮助我的问题:

Application_Error event global.asax not getting triggered

global.asax Application_Error not firing

Application_Error not firing when customerrors = "On"

Is global.asax Application_Error event not fired if custom errors are turned on?

Application_Error does not fire?

Global.asax not firing for .aspx pages in IIS7

事实证明,这些答案毕竟是正确的:

Application_Error does not fire?

Is global.asax Application_Error event not fired if custom errors are turned on?

我最终将代码更改为:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

    Dim ex As Exception = Server.GetLastError

    If TypeOf ex Is System.Web.HttpRequestValidationException Then
        Server.ClearError()
        'NavigateToErrorPage() calls Server.Transfer()

        NavigateToErrorPage("Display special error message here")
    End If

End Sub

旧配置和新配置之间在框架方面肯定发生了一些变化,因为这之前工作正常,因此我感到困惑。这很可能是 IIS 或 MVC 被引入到 webforms 项目中的事实。在这一点上我只能推理,但似乎在 Application_Error 事件中调用 Server.Transfer() 也具有调用 Server.ClearError() 的次要效果。但是,在新的环境中,情况已经不一样了。我敢打赌 Server.Transfer() 确实会尝试导航到自定义页面,但是,由于在事件结束时错误没有被清除,ASP.NET 的默认错误处理会出现并消失用户离开 error.aspx.

所以看起来这毕竟是一个愚蠢的问题,尽管重要的是要留给那些经历过剧烈环境变化并想知道为什么他们从未更改过的代码突然停止工作的人。