compression done!

2007-08-18 @ 19:10#

ha! i love it when things come together. i found a very straight-forward article on how to use .NET 2.0 System.IO.Compression namespace to build an IHttpModule. i was able to implement that code in my framework in just minutes!

in a simple XML example i got some very noticeable bandwidth improvements. check out the before/after traces:

without compression

HTTP/1.1 200 OK Server: Microsoft-IIS/5.1 Date: Sat, 18 Aug 2007 23:14:15 GMT X-Powered-By: ASP.NET X-AspNet-Version: 2.0.50727 X-Exyus: 0.8.2786.32458 2007-08 Last-Modified: Sat, 18 Aug 2007 23:14:15 GMT ETag: meivvKmbEG4V0aXu2C59Ig== Content-Type: text/xml; charset=utf-8 Content-Length: 12554

with compression enabled

HTTP/1.1 200 OK Server: Microsoft-IIS/5.1 Date: Sat, 18 Aug 2007 23:15:41 GMT X-Powered-By: ASP.NET X-AspNet-Version: 2.0.50727 Content-Encoding: gzip X-Exyus: 0.8.2786.32458 2007-08 Last-Modified: Sat, 18 Aug 2007 23:15:41 GMT ETag: meivvKmbEG4V0aXu2C59Ig== Content-Type: text/xml; charset=utf-8 Content-Length: 1565

pretty cool, eh? and the code is really simple. below is the *entire* code set for adding support for streaming compression. just add the code below to your project and add the config entry to your web.config and your all set!

/* <httpModules> <add type="Exyus.Web.HttpCompressionModule, Exyus" name="HttpCompressionModule" /> </httpModules> */ using System; using System.Web; using System.IO.Compression; namespace Exyus.Web { public class HttpCompressionModule : IHttpModule { void IHttpModule.Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void IHttpModule.Dispose(){} void context_BeginRequest(object sender, EventArgs args) { HttpApplication app = sender as HttpApplication; 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"); } } private bool IsEncodingAccepted(string encoding) { return HttpContext.Current.Request.Headers["Accept-encoding"] != null && HttpContext.Current.Request.Headers["Accept-encoding"].Contains(encoding); } private void SetEncoding(string encoding) { HttpContext.Current.Response.AppendHeader("Content-encoding", encoding); } } }

code