asp.net mvc page compression

Looking for a great way to reduce page size and reduce bandwith usage on your asp.net mvc web application?
consider looking into page compression. Below is the c# class that I used to knock my page size down from 44K to a measly 6K...thus saving on bandwidth usage and page download time. 

First, you need to reference the following namespaces

 

using System.IO.Compression;
using System.Web;
using System.Web.Mvc;


 

And then you throw this class together, subclassed by ActionFilterAttribute

public class EnableCompressionAttribute : ActionFilterAttribute
{
  
const CompressionMode compress = CompressionMode.Compress;
  
  
public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
      
HttpRequestBase request = filterContext.HttpContext.Request;
       HttpResponseBase response = filterContext.HttpContext.Response;
       string acceptEncoding = request.Headers["Accept-Encoding"];
       if (acceptEncoding == null)
          
return;
      
else if (acceptEncoding.ToLower().Contains("gzip"))
       {
             response.Filter =
new GZipStream(response.Filter, compress);
             response.AppendHeader(
"Content-Encoding", "gzip");
       }
      
else if (acceptEncoding.ToLower().Contains("deflate"))
       {
             response.Filter =
new DeflateStream(response.Filter, compress);
             response.AppendHeader(
"Content-Encoding", "deflate");
       }
   }
}

then decorate your Controller Methods like so:

[EnableCompression]
public ActionResult Index(string id)
{
......
}

Refresh your page and be prepared to be knowcked off your rockers in terms of the dramatic chnage in page size.

Now this should work in all modern browsers, but for some reason, the latest distribution of Internet Explorer is totally out of the loop as far as this goes.
But it does work with latest version of Opera, Firefox, Safari, Chrome. 

For further reading, check out this article regarding page compression.
http://betterexplained.com/articles/how-to-optimize-your-site-with-gzip-compression/

  

 

12 Comments

Comments have been disabled for this content.