首页 文章

IIS7集成管道模式中的异常处理

提问于
浏览
0

我有一个在集成模式下运行的IIS7上托管的应用程序 . 我通过将以下内容放入Web.config来处理错误:

<httpErrors errorMode="DetailedLocalOnly" existingResponse="Replace" 
            defaultResponseMode="ExecuteURL" defaultPath="/Error.aspx">
  <remove statusCode="500" />
  <error statusCode="500" path="/Error.aspx" responseMode="ExecuteURL" />
</httpErrors>

(因为这是集成模式,所以不使用<customErrors>块 . )

我想在每次生成异常时自动发送电子邮件 . 但问题是在Error.aspx中我无法弄清楚如何获得对异常的引用 . 我试过这个:

Dim oEx As Exception = Server.GetLastError()

但它返回Nothing . 我也尝试过HttpContext.Current.Error()和HttpContext.Current.AllErrors,但这些都不起作用 .

在IIS7集成模式下运行的自定义错误页面中,如何获取对已处理异常的引用?

1 回答

  • 0

    您需要在Global.asax或自定义IHttpModule实现中拦截错误,如下所示:

    public class UnhandledExceptionHandlerModule : IHttpModule {
        private HttpApplication application;
    
        public void Init(HttpApplication application)
        {
            this.application = httpApplication;
            this.application.Error += Application_Error;
        }
    
        public void Dispose()
        {
            application = null;
        }
    
        protected internal void Application_Error(object sender, EventArgs e)
        {
            application.Transfer("~/Error.aspx");
        }
    }
    

    然后,在Error.aspx.cs中:

    protected void Page_Load(object sender, EventArgs e) {
        Response.StatusCode = 500;
    
        // Prevent IIS from discarding our response if
        // <system.webServer>/<httpErrors> is configured.
        Response.TrySkipIisCustomErrors = true;
    
        // Send error in email
        SendEmail(Server.GetLastError());
    
        // Prevent ASP.NET from redirecting if
        // <system.web>/<customErrors> is configured.
        Server.ClearError();
    }
    

相关问题