JumpStart # 47 – GZip/Deflate Compression in ASP.Net MVC Application

In this jumpstart, we are going to see how to implement GZip/Deflate compression in ASP.Net MVC Application. GZip/Deflate compression is used to compress the HTML response which is generated by an ASP.Net MVC Controller Action. This will help in reducing the size of content which is send back to browser in response, there by improving the performance.

Lets get started by creating a new ASP.Net MVC4 Application. Then create the following ActionFilter.

    public class ResponseCompressFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var response = HttpContext.Current.Response;
            var acceptEncodingHeader = HttpContext.Current.Request.Headers["Accept-Encoding"];
            if (!string.IsNullOrEmpty(acceptEncodingHeader) && 
                ((acceptEncodingHeader.Contains("gzip") || acceptEncodingHeader.Contains("deflate"))))
            {
                response.Headers.Remove("Content-Encoding");
                if (acceptEncodingHeader.Contains("gzip"))
                {
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                    response.AppendHeader("Content-Encoding", "gzip");
                }
                else
                {
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                    response.AppendHeader("Content-Encoding", "deflate");
                }
            }
        }
    }

Decorate the created ResponseCompressFilter to Controller (it can also be included in global filters or actions).

    [ResponseCompressFilter]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
            return View();
        }
    }

First lets run the application without filter in Firefox browser.

image

When we include the ResponseCompressFilter and run the application, we get following result.

image

We can clearly see that the content length is less in compressed version of response. We can see bigger difference when we do the same analysis with heavy pages (above analysis is done with ASP.Net MVC4 default Index page).

That’s it for now, Happy Coding and Stay Tuned!!!

You may also like...