Asp.net

用於 IIS 7 的自定義 HttpModule 用於集成

  • October 21, 2012

我在建構自定義錯誤處理程序時遇到問題。它應該是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 配置的。

從我可以看到你在正確的軌道上。您是否確定您站點的應用程序池設置為託管管道模式?

此外,如果您使用內置的 Visual Studio Web 伺服器 (Cassini) 對此進行測試,則該<system.webServer>部分將被忽略。如果您希望從那裡載入模組,則需要 IIS7 或 IIS7.5 Express。

我遇到了這個問題,發現不關閉 customErrors 會阻止處理程序觸發。

即:在您的配置中,要在 HttpModule 中擷取錯誤事件,這是必需的:

<system.web>
   <customErrors mode="Off" />
</system.web>

引用自:https://stackoverflow.com/questions/5911923