2011-07-13 28 views
0

我寫了一個自定義的IHttpModule,但它在源代碼中沒有結束標記時會引發問題。我在CMS中運行了幾頁,我正在運行這個頁面,使用.aspx頁面更像是一個處理程序,並且放棄關閉html以通過ajax給用戶返回響應。IHttpModule Response.Filter Write No Close HTML

這裏是我的源:

public class HideModule : IHttpModule 
{ 
    public void Dispose() 
    { 
     //Empty 
    } 

    public void Init(HttpApplication app) 
    { 
     app.ReleaseRequestState += new EventHandler(InstallResponseFilter); 
    } 

    // --------------------------------------------- 
    private void InstallResponseFilter(object sender, EventArgs e) 
    { 
     HttpResponse response = HttpContext.Current.Response; 

     string filePath = HttpContext.Current.Request.FilePath; 
     string fileExtension = VirtualPathUtility.GetExtension(filePath); 

     if (response.ContentType == "text/html" && fileExtension.ToLower() == ".aspx") 
      response.Filter = new PageFilter(response.Filter); 
    } 
} 

public class PageFilter : Stream 
{ 
    Stream   responseStream; 
    long   position; 
    StringBuilder responseHtml; 

    public PageFilter (Stream inputStream) 
    { 
     responseStream = inputStream; 
     responseHtml = new StringBuilder(); 
    } 

    //Other overrides here 

    public override void Write(byte[] buffer, int offset, int count) 
    { 
     string strBuffer = System.Text.UTF8Encoding.UTF8.GetString (buffer, offset, count); 

     Regex eof = new Regex ("</html>", RegexOptions.IgnoreCase); 

     if (!eof.IsMatch (strBuffer)) 
     { 
      responseHtml.Append (strBuffer); 
     } 
     else 
     { 
      responseHtml.Append (strBuffer); 

      string finalHtml = responseHtml.ToString(); 

      //Do replace here 

      byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(finalHtml); 

      responseStream.Write(data, 0, data.Length); 
     } 
    } 
    #endregion 
} 

正如你可以看到這是偉大的,因爲它不僅替換最後一次寫被調用,但是如果輸出不關閉HTML標記,blammo 。

我最好的選擇是甚至不添加新的過濾器,如果沒有找到關閉HTML。但我不認爲我可以儘早攔截全部流。如果失敗了,還有另一種檢測Write的方法,除了查找結束html標籤外,還在流的末尾?

在此先感謝。

回答

0

好吧,如果這是WebForms的,你應該能夠做這樣的事情在你的InstallResponseFilter功能:

if(Application.Context.CurrentHandler is System.Web.UI.Page 
        && Application.Request["HTTP_X_MICROSOFTAJAX"] == null 
        && Application.Request.Params["_TSM_CombinedScripts_"] == null) 
{ 
response.Filter=new PageFilter(response.Filter); 
}