65.9K
CodeProject is changing. Read more.
Home

Compress Aspx with GZip

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (4 votes)

May 7, 2009

GPL3
viewsIcon

31122

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