您可以使用HttpModule
有条件地分配给HttpResponse.Filter
拦截和处理HttpResponse.Write
使用的自定义来完成此操作。
模块示例
此示例使用Content-Type
request.Header 的值来确定是否应应用 html 编码。
public class FilterResponseWriteModule : IHttpModule, IDisposable
{
private System.IO.Stream filterStream;
public FilterResponseWriteModule()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += Context_BeginRequest;
}
private void Context_BeginRequest(object sender, EventArgs e)
{
var context = (sender as HttpApplication).Context;
if (ShouldApplyFilter(context.Request))
ApplyFilter(context.Response);
}
private bool ShouldApplyFilter(HttpRequest request)
{
return string.Equals(request.ContentType, @"text/plain", StringComparison.OrdinalIgnoreCase);
}
private void ApplyFilter(HttpResponse response)
{
filterStream = new EncodeStreamFilter(response.Filter);
response.Filter = filterStream;
}
public void Dispose()
{
if (filterStream != null)
{
filterStream.Dispose();
}
}
}
过滤流示例(封装和覆盖)
Stream 是一个抽象类,因此它将生成所有相关的覆盖方法存根。
public class EncodeStreamFilter : Stream, IDisposable
{
private Stream _baseStream;
public EncodeStreamFilter(Stream responseFilter)
{
_baseStream = responseFilter;
}
public override void Write(byte[] buffer, int offset, int count)
{
byte[] bufferBlock = new byte[count];
Buffer.BlockCopy(buffer, offset, bufferBlock, 0, count);
var encodedBytes = Encoding.UTF8.GetBytes(HttpUtility.HtmlEncode(Encoding.UTF8.GetString(bufferBlock)));
_baseStream.Write(encodedBytes, 0, encodedBytes.Length);
}
public override bool CanRead
{
get
{
return _baseStream.CanRead;
}
}
public override bool CanSeek
{
get
{
return _baseStream.CanSeek;
}
}
public override bool CanWrite
{
get
{
return _baseStream.CanWrite;
}
}
public override long Length
{
get
{
return _baseStream.Length;
}
}
public override long Position
{
get
{
return _baseStream.Position;
}
set
{
_baseStream.Position = value;
}
}
public override void Flush()
{
_baseStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return _baseStream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _baseStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
_baseStream.SetLength(value);
}
protected override void Dispose(bool disposing)
{
if (!disposing)
{
_baseStream.Dispose();
}
base.Dispose(disposing);
}
}
将模块添加到 Web.Config
注意:在这种情况下,我将模块定义为我的应用程序的 App_Start 文件夹中的一个类。
<system.webServer>
<modules>
<add name="FilterResponseWriteModule" type="HttpModulesTestApp.App_Start.FilterResponseWriteModule"/>
</modules>
</system.webServer>