8

我在构建自定义错误处理程序时遇到问题。它应该是HttpModule,但是当我将它添加到我web.configsystem.webServer/modules标签时,它不会被启动。

这是我的web.config部分:

<system.webServer>
  <modules>
    <add name="AspExceptionHandler" 
         type="Company.Exceptions.AspExceptionHandler, Company.Exceptions" 
         preCondition="managedHandler" />
  </modules>
</system.webServer>

这是我的代码HttpModule

using System;
using System.Web;
using Company.Settings;
using System.Configuration;

namespace Company.Exceptions
{
  public class AspExceptionHandler : IHttpModule
  {
    public void Dispose() { }

    public void Init(HttpApplication application)
    {
      application.Error += new EventHandler(ErrorHandler);
    }

    private void ErrorHandler(object sender, EventArgs e)
    {
      HttpApplication application = (HttpApplication)sender;
      HttpContext currentContext = application.Context;

      // Gather information5
      Exception currentException = application.Server.GetLastError();
      String errorPage = "http://www.mycompaniesmainsite.com/error.html";

      HttpException httpException = currentException as HttpException;
      if (httpException == null || httpException.GetHttpCode() != 404)
      {          
        currentContext.Server.Transfer(errorPage, true);
      }
      else
      {
        application.Response.Status = "404 Not Found";
        application.Response.StatusCode = 404;
        application.Response.StatusDescription = "Not Found";
        currentContext.Server.Transfer(errorPage, true);
      }
    }
  }
}

有人可以向我解释我做错了什么,以及 IIS 7 集成托管管道模式是如何工作的吗?因为我找到的大多数答案都是关于HttpModules为 IIS 6 配置的。

4

3 回答 3

3

从我可以看到你在正确的轨道上。您是否确定您站点的应用程序池设置为托管管道模式?

此外,如果您使用内置的 Visual Studio Web 服务器 (Cassini) 对此进行测试,则该<system.webServer>部分将被忽略。如果您希望从那里加载模块,则需要 IIS7 或 IIS7.5 Express。

于 2011-05-07T00:58:00.373 回答
0

通过对上述代码进行以下更改,我遇到了未触发的处理程序的相同问题,帮助我解决了此问题。我没有创建新的事件处理程序,而是将具有相同签名的方法附加到该事件。

application.Error += ErrorHandler;

这对我有用,仍在分析在 IIS7 中附加处理程序的这种方式背后的原因。

于 2012-05-16T15:21:39.607 回答
0

我遇到了这个问题,发现不关闭 customErrors 会阻止处理程序触发。

即:在您的配置中,要在 HttpModule 中捕获错误事件,这是必需的:

<system.web>
    <customErrors mode="Off" />
</system.web>
于 2012-08-07T06:38:01.117 回答