//Karthik Srinivasan

Product Engineer, CTO & a Beer Enthusiast
Experiments, thoughts and scripts documented for posterity.

Quirky Personal Projects

LinkedIn

Email me

Unhandled GZip Encoding - ASP.NET

Mar, 2010

What happens when you have GZip turned on and there is an unhandled exception is thrown, look no further.. a completely cryptic garbage page is returned



So whats the problem, well when an unhandled exception is thrown ASP.NET/MVC removes the GZip header or any other custom header that was set and returns a non-zipped content while your IIS decides to send to browser that the content is GZipped when it's not really. So your browser is receiving a non-zipped content with GZIP content type, thus the garbage content.

To fix this in the global.ascx add the following to the Application_PreSendRequestHeaders function:
protected void Application_PreSendRequestHeaders()
{  
  if (HttpContext.Current != null && HttpContext.Current.Response != null)
  {
     HttpResponse response = HttpContext.Current.Response;
     if (response.Filter is GZipStream && 
           response.Headers["Content-encoding"] != "gzip")
        {
           response.AppendHeader("Content-encoding", "gzip");
        }
      else if (response.Filter is DeflateStream && 
           response.Headers["Content-encoding"] != "deflate")
        {
           response.AppendHeader("Content-encoding", "deflate");
        }
   }
}