Introduction
This is a simple function to compress your aspx page with GZip.
Background
If you need advanced knowledge about compression, please visit this link.
Using the Code
Just call this function in the page render:
protected override void Render(HtmlTextWriter writer)
{
doCompression();
base.Render(writer);
}
The method:
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();
response.Filter = new GZipStream(context.Response.Filter,
CompressionMode.Compress);
if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding",
"gzip");
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding",
"deflate");
}
}
response.Cache.VaryByHeaders["Accept-Encoding"] = true;
}
History
- 7th May, 2009: Initial post