2012-02-06 57 views
5

考慮一個Web.config文件包含以下httpHandlers聲明:如何獲取對默認ASP.NET頁面處理程序或Web服務處理程序的引用?

<httpHandlers> 
    <add verb="*" path="*" type="MyWebApp.TotalHandlerFactory"/> 
</httpHandlers> 

換句話說,此處理廠要「看」的所有傳入的請求,使其得到一個機會來處理它們。然而,它並不一定要真正處理所有的人,只有那些滿足一定的運行時間條件:

public sealed class TotalHandlerFactory : IHttpHandlerFactory 
{ 
    public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) 
    { 
     if (some condition is true) 
      return new MySpecialHttpHandler(); 

     return null; 
    } 

    public void ReleaseHandler(IHttpHandler handler) { } 
} 

但是,這樣做就這樣完全覆蓋默認ASP.NET處理程序,這意味着ASP.NET頁面和Web服務不再有效。我只是爲每個不符合「if」條件的網址獲得一個空白頁面。因此,似乎返回null是不對的。

那麼我需要返回什麼,以便ASP.NET頁面和Web服務仍能正常處理?

+0

我意識到它是HttpHandlerFactory不是處理程序本身。 – Aliostad 2012-02-06 15:55:53

回答

0

在一般情況下無法做到這一點。

2

我原以爲最簡單的方法是讓你的班級繼承System.Web.UI.PageHandlerFactory,然後在其他子句中調用base.GetHandler()

public sealed class TotalHandlerFactory : System.Web.UI.PageHandlerFactory 
{ 
    public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) 
    { 
     if (some condition is true) 
      return new MySpecialHttpHandler(); 
     else 
      return base.GetHandler(context, requestType, url, pathTranslated) 
    } 
} 
+1

這適用於網頁,但不適用於網絡服務... – Timwi 2012-02-06 16:10:19

+0

嗯..不知道那麼。這是我曾經躺過的代碼,但它不需要Web服務。我看不到任何其他創建基本處理程序的簡單方法。 :( – Chris 2012-02-06 16:30:32

0

不知道您的所有要求,聽起來像一個HttpModule是一個更適合您的問題的解決方案。

2

我有同樣的問題,似乎這樣做是不可能的使用HttpHandlerFactory。

但是,我發現了一個變通方法,解決了這個問題:使用一個HttpModule過濾哪些請求應該去我的自定義的HttpHandler:

首先,從web.config中刪除任何引用到你HttpHandler

然後,添加以下的HttpModule的引用<Modules>段內:

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

    public void Init(HttpApplication application) 
    { 
     application.PostAuthenticateRequest += new EventHandler(application_PostAuthenticateRequest); 
    } 

    void application_PostAuthenticateRequest(object sender, EventArgs e) 
    { 
     var app = sender as HttpApplication; 
     var requestUrl = context.Request.Url.AbsolutePath; 

     if (requestUrl "meets criteria") 
     { 
      app.Context.RemapHandler(new MyHttpHandler()); 
     } 
    } 

} 

最後,假設你的HttpHandler的所有傳入的請求滿足您的條件,處理那裏所有的請求。

相關問題