Compress HttpResponse for your controller actions using attributes
If you have ever ran the FireFox plugins PageSpeed (google) or YSlow (yahoo) you would have received a lot of insight & help into what you can do to speed up you website pages. This is of course important for developing scalable websites and providing a better experience for your visitors. If you are like many other developers, you would have ignored a lot of things or possibly not taken action because you didn't know you should have. Your resulting score will not be very high - let's say average. If you do want to stand out above the crowd using a simple technique, read on.
I took action a while back to address the issues highlighted by these tools I have found huge improvement is website performance, plus since google is now ranking also on page speed it will no doubt improve you standing with this search engine - google only has a small share of the market, right!?. View search engine market share.
This technique saves developers a lot of time, but still very important, easily informs them as to what is happening with their controller action and their Http Response. Part of my philosophy of easy maintenance over complexity where possible.
Using statements:
using System; using System.IO.Compression; using System.Web; using System.Web.Mvc;
Compress Attribute:
public class CompressResponseAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (!String.IsNullOrEmpty(acceptEncoding))
{
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
}
Simply add this attribute to your controller action and off you go. The response gets GZip / Deflate and sent to who / what has requested your page.
Usage:
[CompressResponse]
public ActionResult Index()
{
return View();
}
Simple isn't it. Feel free to leave any comments.
>I have been visiting vauoirs blogs for my term papers writing research. I have found your blog to be quite useful. Keep updating your blog with valuable information Regards
Thanks Richard.. It seems very cool...
Just a question: I read about remove white space too.
What about use this removal space code: http://madskristensen.net/post/Remove-whitespace-from-your-pages.aspx before compressing?
Thanks!