Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Compress Aspx with GZip

0.00/5 (No votes)
7 May 2009 1  
A simple function to compress aspx page

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here