The new System.IO.Compression namespace in .NET 2.0 makes it easy to implement HTTP compression without having to touch IIS. The best thing about it is that you no longer need any third party compression components, it’s all build directly into .NET Framework.

There are different ways to implement the compression but I think an HttpModule is the right choice for this feature. Let's create one and call it CompressionModule.

The CompressionModule must adhere to the following rules:

  • Support both GZip and Deflate compression
  • Only compress if the browser supports it
  • Simplest possible implementation

These rules are important to make sure that the compression will run smoothly in every situation.

The code

An HttpModule is a class that implements the IHttpModule interface and gives it direct access to the underlying HttpApplication. We have to implement the Init method and attach the Application.BeginRequest event and the event handler that will do the compression.

#regionUsing usingSystem;usingSystem.Web;usingSystem.IO.Compression; #endregion ///<summary>///Compresses the output using standard gzip/deflate.///</summary>publicclassCompressionModule:IHttpModule{  #regionIHttpModule Members  voidIHttpModule.Dispose() {   // Nothing to dispose; }  voidIHttpModule.Init(HttpApplicationcontext) {   context.BeginRequest +=newEventHandler(context_BeginRequest); }  #endregion  #regionCompression  privateconststringGZIP ="gzip"; privateconststringDEFLATE ="deflate";  voidcontext_BeginRequest(objectsender,EventArgse) {   HttpApplication app = sender as HttpApplication;   if (app.Request.RawUrl.Contains(".aspx"))   {     if (IsEncodingAccepted(GZIP))     {       app.Response.Filter = new GZipStream(app.Response.Filter, CompressionMode.Compress);       SetEncoding(GZIP);     }     else if (IsEncodingAccepted(DEFLATE))     {       app.Response.Filter = new DeflateStream(app.Response.Filter, CompressionMode.Compress);       SetEncoding(DEFLATE);     }   }

> }  ///<summary> ///Checks the request headers to see if the specified ///encoding is accepted by the client. ///</summary> privateboolIsEncodingAccepted(stringencoding) {   returnHttpContext.Current.Request.Headers["Accept-encoding"] !=null&&HttpContext.Current.Request.Headers["Accept-encoding"].Contains(encoding); }  ///<summary> ///Adds the specified encoding to the response headers. ///</summary> ///<param name="encoding"></param> privatevoidSetEncoding(stringencoding) {   HttpContext.Current.Response.AppendHeader("Content-encoding", encoding); }  #endregion 



Download the CompressionModule.cs file below and add it to the App_Code folder in the root of your website. Then add these lines to the web.config’s <system.web> section.

 <httpModules>  <addtype="CompressionModule"name="CompressionModule"/> </httpModules>

That’s all you have to do to enable HTTP compression on an ASP.NET 2.0 website.



CompressionModule.zip (0,75 KB)