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()

但它什么都不返回。我还尝试了 HttpContext.Current.Error() 和 HttpContext.Current.AllErrors ,但它们也不起作用。

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

4

1 回答 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();
}
于 2010-03-23T21:52:52.323 回答