Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Compression ActionFilter, Server error messages clears content-encoding header and renders as gibberish

When I'm using a compression filter and get an error, the error page is just gibberish characters. The problem seems to be that when IIS transfers to the error page the compression filter is still in effect, but the headers are cleared. Without the "Content-encoding: gzip" header the browser just displays the raw gzipped binary data.

I'm using IIS7.5, ASP.NET MVC 2 Preview 2 and an ActionFilter that looks like this:

public class CompressResponseAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var request = filterContext.HttpContext.Request;
        var response = filterContext.HttpContext.Response;

        var acceptEncoding = request.Headers["Accept-Encoding"];

        if (string.IsNullOrEmpty(acceptEncoding))
            return;

        acceptEncoding = acceptEncoding.ToLowerInvariant();

        if (acceptEncoding.Contains("gzip"))
        {
            response.AppendHeader("Content-encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        }
        else if (acceptEncoding.Contains("deflate"))
        {
            response.AppendHeader("Content-encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
        }
    }
}

Anyone else experienced this?

like image 598
rmac Avatar asked Nov 03 '09 15:11

rmac


1 Answers

Update: I stumbled upon Rick Strahl's blog post on this and other problems with compression. See here: http://www.west-wind.com/weblog/posts/2011/May/02/ASPNET-GZip-Encoding-Caveats

His solution, which seems more reliable, is to put the following in Global.asax.cs:

protected void Application_Error(object sender, EventArgs e)
{
    // Remove any special filtering especially GZip filtering
    Response.Filter = null;
}

Original answer: I fixed this by applying the compression in OnResultExecuting instead of OnActionExecuting.

like image 89
rmac Avatar answered Nov 27 '22 13:11

rmac