You can accomplish this with the Custom HttpModule
, which conditionally assigns HttpResponse.Filter
to intercept and handle HttpResponse.Write
usage.
Module example
This example uses the Content-Type
value for request.Header to determine whether to use html encoding.
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 Filter Example (Encapsulation and Override)
Stream is an abstract class, so it will generate all the corresponding stubs of the override method.
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); } }
Add module to Web.Config
Note. In this case, I defined the module as a class in the App_Start folder of my application.
<system.webServer> <modules> <add name="FilterResponseWriteModule" type="HttpModulesTestApp.App_Start.FilterResponseWriteModule"/> </modules> </system.webServer>
source share