4

HttpModule 工作正常(“hello”被替换为“hello world”),但由于某些原因,当模块添加到 Web.config 时,WebForms 上的图像不显示。从 Web.config 中删除模块后,将显示 WebForms 上的图像。

有谁知道为什么?

使用或不使用 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);
        }
}

//过滤器 - 将“hello”替换为“hello world”

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

2 回答 2

4

您是否将模块应用于所有请求?您不应该这样做,因为它会弄乱任何二进制文件。您可能只是让您的事件处理程序仅在内容类型合适时应用过滤器。

不过,最好只将模块应用于特定的扩展。

老实说,您的流实现也有点狡猾 - 对于以 UTF-8 编码时占用多个字节的字符,它可能会失败,并且即使只写入部分缓冲区,您也在解码整个缓冲区。此外,您可能会将“hello”拆分为“he”,然后是“llo”,这是您目前无法处理的。

于 2009-09-13T13:26:41.947 回答
3

尝试这样做,这只会为 aspx 页面安装过滤器,所有其他 url 都可以正常工作。

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

有几个属性,您必须尝试使用​​ Response.Url.AbsolutePath 或其他一些可以提供完美结果的代码。

于 2009-09-13T13:24:36.483 回答