2009-09-13 69 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