I have a custom HttpHandler in which I manually enable output compression, for example:
context.Response.AppendHeader("Content-encoding", "gzip");
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
This works well for most requests, but when an exception occurs, the "Content-encoding" header disappears from the response, while the compression filter remains in place. As a result, the gzip error page is compressed, but the browser does not receive a header indicating this fact. Then the browser tries to display the still compressed data in the form of text that gobbledygook .
The full code for the test code is shown below. Try disabling compression one at a time or not throwing an exception.
Can someone shed some light on why the "Content-encoding" header disappears?
I suppose I can just turn on compression as the last thing the handler does, so if an exception occurs, it never reaches the point where the compression filter is added; but the behavior that I see amazes me like a mistake. Can anyone confirm?
public class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
CompressResponse(context);
context.Response.Write("Hello world");
throw new Exception("Just testing...");
}
private void CompressResponse(HttpContext context)
{
string acceptEncoding = context.Request.Headers["Accept-Encoding"];
if (String.IsNullOrEmpty(acceptEncoding))
{
return;
}
if (acceptEncoding.ToLower().Contains("gzip") || acceptEncoding.Contains("*"))
{
context.Response.AppendHeader("Content-encoding", "gzip");
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
return;
}
}
public bool IsReusable
{
get { return true; }
}
}
EDIT: Screenshot of the still encoded answer that I see in my test case: http://i.imgur.com/49Vcl.png
source
share