[英]Testing HttpModule wtih Response.Filter and Response.Write
[英]HttpModule, Response.Filter, and images not displayed
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);
}
}
您是否将模块应用于所有请求? 你不应该,因为它会弄乱任何二进制文件。 您可能只是让事件处理程序仅在内容类型合适时应用过滤器。
尽管如此,最好只将模块应用于特定扩展。
说实话,你的流实现也有点狡猾 - 对于在UTF-8编码时占用多个字节的字符可能会失败,并且即使只写入其中的一部分,你也要解码整个缓冲区。 另外,你可能会把“你好”分成“他”,然后分开你当前没有应对的“llo”。
尝试这样做,这将只安装aspx页面的过滤器,所有其他网址将正常工作。
void OnBeginRequest(object sender, EventArgs e)
{
if(Request.Url.ToString().Contains(".aspx"))
application.Response.Filter = new MyStream(application.Response.Filter);
}
有几个属性,您必须尝试使用Response.Url.AbsolutePath或其他一些能够提供完美结果的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.