Thursday, June 11, 2009

Compress Response

It is obvious that we need to compress our response while passing to the client. Compress requests and response are always increases performance of sites. Nowadays, almost 99 percent of the browsers supports either Gzip or Deflate compression or both. So if we can check if accept-encoding header is present and return compressed response to the client, then we have just improved our site performance. Just take a look on the code below :

public static void doCompression()
{
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
HttpResponse response = context.Response;
if (!string.IsNullOrEmpty(acceptEncoding))
{
acceptEncoding = acceptEncoding.ToUpperInvariant();
if (acceptEncoding.Contains("GZIP"))
{
response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
response.AppendHeader("Content-encoding", "gzip");
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.Filter = new DeflateStream(context.Response.Filter, CompressionMode.Compress);
response.AppendHeader("Content-encoding", "deflate");
}
}
response.Cache.VaryByHeaders["Accept-Encoding"] = true;
}


Here we are checking if the Request header contains [“Accept-Encoding”]. Based on the encoding it supports we filter the response using GZipStream / DeflateStream which are available in System.IO.Compression namespace. Thus the response will be compressed.
Only this will not help the client to render your page properly. You need to add the Content-Encoding header to the response, so it can decompress the response in the client properly. We add Response header “Accept-Encoding” so that request is also made from now using the same encoding it is sending the data.

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!