2009-09-13 68 views
4

HttpModule工作正常(「hello」替換爲「hello world」),但由於某些原因,當將模塊添加到Web.config時,WebForms上的圖像不顯示。從Web.config中刪除該模塊時,將顯示WebForms上的圖像。HttpModule,Response.Filter和圖像未顯示

有誰知道爲什麼?

使用或不使用HttpModule生成的HTML完全相同!

//The HttpModule 

public class MyModule : IHttpModule 
{ 
     #region IHttpModule Members 

     public void Dispose() 
     { 
      //Empty 
     } 

     public void Init(HttpApplication context) 
     { 
      context.BeginRequest += new EventHandler(OnBeginRequest); 
      application = context; 
     } 

     #endregion 

     void OnBeginRequest(object sender, EventArgs e) 
     { 
      application.Response.Filter = new MyStream(application.Response.Filter); 
     } 
} 

//過濾器 - 替換「你好」與「世界你好」

public class MyStream : MemoryStream 
{ 
     private Stream outputStream = null; 

     public MyStream(Stream output) 
     { 
      outputStream = output; 
     } 

     public override void Write(byte[] buffer, int offset, int count) 
     { 

      string bufferContent = UTF8Encoding.UTF8.GetString(buffer); 
      bufferContent = bufferContent.Replace("hello", "hello world"); 
      outputStream.Write(UTF8Encoding.UTF8.GetBytes(bufferContent), offset, UTF8Encoding.UTF8.GetByteCount(bufferContent)); 

      base.Write(buffer, offset, count); 
     } 
} 

回答

4

您是否將模塊應用於所有請求?你不應該這樣做,因爲它會弄亂任何二進制的東西。你可能會讓你的事件處理程序只在內容類型合適時才應用過濾器。

最好只將模塊應用於特定的擴展以開始。

說實話,你的流的實現也有些狡猾 - 對於以UTF-8編碼時佔用多個字節的字符可能會失敗,並且即使只寫入了一部分字節。此外,您可能會將「hello」分解爲「他」,然後分解爲您目前無法處理的「llo」。

+0

使事件處理程序在.aspx頁面上應用篩選器只做了它。謝謝您的幫助。 – thd 2009-09-15 22:56:04

3

嘗試這樣做,這樣只會對aspx頁面安裝過濾器,以及其他所有網址將正常工作。

void OnBeginRequest(object sender, EventArgs e)  
{ 
    if(Request.Url.ToString().Contains(".aspx"))   
     application.Response.Filter = new MyStream(application.Response.Filter);  
} 

有幾個屬性,你必須嘗試使用​​Response.Url.AbsolutePath或一些其他的代碼,會給出完美的結果。

+0

謝謝!您的代碼建議有效。 – thd 2009-09-15 22:56:45