如何禁用 IIS 错误页面并处理 Global.asax 中的错误?

How Do I Disable IIS Error Pages And Handle Errors In Global.asax?

提问人:MatthewNYC 提问时间:5/10/2022 更新时间:5/10/2022 访问量:349

问:

我一直在尝试禁用IIS错误处理,以便可以捕获Global.asax中的所有错误。

我正在运行 Windows 2012 和 IIS 版本 6.2。

例如,当我导航到丢失的图像文件时,例如:

www.mysite.com/thisimagesdoesntexist.jpg

我收到 IIS 错误页面,但我的 Global.asax 没有捕获错误。

我尝试添加到我的web.config:

<system.webServer>
<httpErrors existingResponse="Passthrough" />
</system.webServer>

而且,在 Global.asax 中:

Server.ClearError()
Response.TrySkipIisCustomErrors = True

但是,缺少图像错误仍由 IIS 处理。下面是我的 web.config 和 Global.asax 例程的代码:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <!--Unobtrusive validation used JQuery-->
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />
  </appSettings>
  <system.web>
    <httpRuntime targetFramework="4.6.1" />
    <!--Enable Sessions and don't scroll a form when doing a postback-->
    <!-- clientIDMode="Static" ensures the ASP.net controls have the exact name specified in their ID tags
         This is important so CSS targets the correct IDs for styling. -->
    <pages enableSessionState="true" controlRenderingCompatibilityVersion="3.5" clientIDMode="Static" maintainScrollPositionOnPostBack="true" />
    <!--Use cookies if enabled; use querystring if disabled-->
    <!--<sessionState mode="InProc" cookieless="AutoDetect" timeout="20" />-->
    <!-- cookieless="AutoDetect" is adding a cookie parameter to the URL that was causing FastSpring posts to fail -->
    <sessionState mode="InProc" timeout="20" />
    <!--Show detailed errors on the website while developing-->
    <customErrors mode="Off" />
    <compilation debug="true" targetFramework="4.6.1" />
    <!--Use Tracing-->
    <trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false" />
    <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" culture="auto" uiCulture="auto" />
  </system.web>
  <!--
  <system.webServer>
    <httpErrors errorMode="Detailed" />
  </system.webServer>
  -->
  <system.webServer>
    <httpErrors existingResponse="Passthrough" />
  </system.webServer>
  <system.codedom>
    <compilers>
      <compiler extension=".cs" language="c#;cs;csharp" warningLevel="4" compilerOptions="/langversion:7.0 /nowarn:1659;1699;1701;612;618" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=3.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
      <compiler extension=".vb" language="vb;vbs;visualbasic;vbscript" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008,40000,40008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=3.6.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    </compilers>
  </system.codedom>
</configuration>
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

  Dim Uri As Uri = New Uri(Request.Url.AbsoluteUri)

  Dim ex As HttpException = CType(Server.GetLastError(), HttpException)
  Dim httpCode As Integer = ex.GetHttpCode()
  Dim strErrorDescription As String = ex.Message.ToString

  Server.ClearError()
  Response.TrySkipIisCustomErrors = True

  If httpCode = 500 Then
    Response.Redirect("~/error.aspx?type=globalerror&errdescription=" & HttpUtility.UrlEncode(strErrorDescription) & "&url=" & HttpUtility.UrlEncode(Uri.ToString))
  ElseIf httpCode = 404 Then
    Response.Redirect("~/404.aspx?type=globalhttp&errdescription=" & HttpUtility.UrlEncode(strErrorDescription) & "&url=" & HttpUtility.UrlEncode(Uri.ToString))
  Else
    'Let's see what other errors are picked up and logged. Perhaps we log these to a separate table?
    Response.Redirect("~/error.aspx?type=globalhttp&errdescription=" & HttpUtility.UrlEncode(strErrorDescription) & "&url=" & HttpUtility.UrlEncode(Uri.ToString))
  End If

End Sub
asp.net IIS 错误处理

评论

0赞 Bruce Zhang 5/10/2022
对静态文件的请求不会进入 asp.net 路由,但 IIS 会转到相应的文件夹以查找资源。因此,该错误页是由 IIS 而不是 asp.net 应用程序引发的。无法禁用 IIS 错误页。除非您让应用程序根据代码中的某个物理路径读取图像,并且读取失败会引发异常。否则,直接请求图像只会使 IIS 始终响应错误页。
0赞 Lex Li 5/10/2022
如果您对 IIS/ASP.NET 体系结构有更多了解,learn.microsoft.com/en-us/iis/application-frameworks/... 你会看到静态文件和 ASP.NET 页由不同的处理程序处理,因此它们的错误是单独处理的。统一业务逻辑来处理这两种错误比您想象的要复杂(至少 Microsoft 没有好的解决方案)。
0赞 MatthewNYC 5/11/2022
我的计划是将所有错误记录到数据库的错误表中。你是说没有办法捕获错误,除非它们确实发生在 asp.net 代码本身中?如果没有,我将在哪里运行IIS遇到的错误的报告?

答: 暂无答案