How to implement GZip compression in ASP.NET?

Prashant picture Prashant · Feb 16, 2009 · Viewed 93.4k times · Source

I am trying to implement GZip compression for my asp.net page (including my CSS and JS files). I tried the following code, but it only compresses my .aspx page (found it from YSlow)

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

The above code is only compressing my .aspx page code (markup) not the CSS and JS files which is included as external files. Please tell me how can I implement GZip compression in ASP.NET using code (because I am on shared hosting server where I don't have access to IIS Server configurations). And also in the above code I am not getting the last two lines, why they are used and what's the purpose of these lines. Please explain!

Answer

dortzur picture dortzur · Dec 11, 2010

Here is the solution for css and javascript files. Add the following code to <system.webServer> inside your web.config file:

<configuration>
  ...
  <system.webserver>
     ...
      <httpCompression>
        <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
        <dynamicTypes>
          <add mimeType="text/*" enabled="true"/>
          <add mimeType="message/*" enabled="true"/>
          <add mimeType="application/javascript" enabled="true"/>
          <add mimeType="*/*" enabled="false"/>
        </dynamicTypes>
        <staticTypes>
          <add mimeType="text/*" enabled="true"/>
          <add mimeType="message/*" enabled="true"/>
          <add mimeType="application/javascript" enabled="true"/>
          <add mimeType="*/*" enabled="false"/>
        </staticTypes>
      </httpCompression>
      <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
    ...
  </system.webserver>
  ...
<configuration>

Credit: How to GZip on ASP.NET and GoDaddy