Global.asax中的Application_Error事件在IIS7中未触发,但在IIS6中正常工作

问题描述:

去年,我们将Web应用程序移至新服务器。以下是前移动系统/应用程序配置规格:Global.asax中的Application_Error事件在IIS7中未触发,但在IIS6中正常工作

  • 的Windows Server 2003
  • IIS 6.0
  • ASP.NET 4.0
  • 的WebForms

这里是移动后的规格到新服务器:

  • Windows Server 2008
  • IIS 7.5
  • ASP.NET 4.5.1
  • 的WebForms/MVC 5混合(感谢VS 2013)

的问题是,在后环境由于移动剧变, Global.asax中的Application_Error事件不再像以前那样触发。我在这方面遇到了很多问题(请参阅本问题的结尾),但没有一个解决方案似乎可行。他们也很古老,所以我认为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 

在web.config中customErrors

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

那么,我需要做的就是我的应用程序在IIS 7.5的行为它IIS 6的行为方式一样吗?

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

我发现的其他问题,无法在这里帮助我:

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 

东西肯定会改变旧的配置框架之间的框架n和新的,因为这之前工作正常,因此我的困惑。这很可能是IIS或者MVC引入webforms项目的事实。我只能在这一点上进行理论研究,但似乎在Application_Error事件中调用Server.Transfer()也具有调用Server.ClearError()的次要效果。但是,在新的环境下,情况已经不复存在。我打赌Server.Transfer()确实尝试导航到自定义页面,但是,由于错误没有在事件结束时被清除,所以ASP.NET的默认错误处理进入并将用户转移到error.aspx

因此,看起来好像这是一个愚蠢的问题,尽管对于任何经历剧烈环境变化的人来说保留这些问题很重要,并且奇怪为什么他们从未进行过更改的代码突然停止工作。