2013-03-20 46 views
1

使用Microsoft.Web.Infrastructure組件,我們可以在應用前的啓動階段登記模塊,如下:註冊自定義PageHandlerFactory通過代碼

DynamicModuleUtility.RegisterModule(typeof(MyHttpModule)); 

是否有可能在ASP註冊自定義PageHandlerFactory。 NET代碼中的web表單而不是像上面的模塊一樣?

我目前這個絲通過這樣的代碼,但我覺得它太冗長(這使得它更難創建快速啓動NuGet包,因爲我改變web.config中):

<?xml version="1.0"?> 
<configuration> 
    <system.webServer> 
    <handlers> 
     <add name="CustomFactory" verb="*" path="*.aspx" 
     type="Shared.CustomPageHandlerFactory, Shared"/> 
    </handlers> 
    </system.webServer> 
</configuration> 

回答

1

據我所知,在代碼中沒有辦法做到這一點。然而,在我的特殊情況下,解決方案確實是註冊一個HTTP模塊。

HTTP模塊可以在初始化時掛接到HttpApplication.PreRequestHandlerExecute事件,該事件在頁面處理程序工廠創建頁面後但在ASP.NET開始執行該頁面(以及其他處理程序)之前執行。

這裏是這樣的HTTP模塊的一個例子:

public class MyHttpModule : IHttpModule 
{ 
    void IHttpModule.Dispose() { 
    } 

    void IHttpModule.Init(HttpApplication context) { 
     context.PreRequestHandlerExecute += 
      this.PreRequestHandlerExecute; 
    } 

    private void PreRequestHandlerExecute(object s, EventArgs e) { 
     IHttpHandler handler = 
      this.application.Context.CurrentHandler; 

     // CurrentHandler can be null 
     if (handler != null) { 
      // TODO: Initialization here. 
     }    
    } 
}