Looking for a great way to reduce page size and reduce bandwith usage on your asp.net mvc web application at the same time? Consider looking into page compression. Below is sample C# class used to reduce page size down by about 80%...thus saving on bandwidth usage and page download time.

First, create a new class, and add the following using statements:

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

Derive your class from ActionFilterAttribute. The completed class is depicted below:

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)
       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:

public ActionResult Index(string id)

Refresh refresh your corresponding view pages and note the significant reduction in page size.