Click here to Skip to main content
14,388,907 members

Improve the Performance of ASP.NET MVC Web Application Using HTTP Compression

Rate this:
4.81 (10 votes)
Please Sign up or sign in to vote.
4.81 (10 votes)
27 Feb 2016CPOL
Use of HTTP Compression on ASP.NET / MVC pages using IIS or Server side code

Introduction

Getting close to HTTP allows you to take advantage of the protocol. This means I can fully leverage features of HTTP such as caching, etags, status codes and the like. One of the important features of HTTP is Default Support for Compression.

Compression is a simple, effective way to save bandwidth and speed up your site. One of the major advantages of using HTTP protocol is default support of data compression using gzip/deflate including caching, etags. There is a lot of information available on this topic but no article explaining it with proof of concept. This article explains how to configure and verify HTTP Compression using Fiddler and trust me, it is fairly easy to do.

Determining Current request/response Encoding

In case you are using the localhost machine as a hosting environment for IIS and you don't see HTTP request and response in fiddler, then we need to make an entry in web.config file to make Fiddler as a proxy for each HTTP request.

<system.net>
  <defaultProxy useDefaultCredentials="true" enabled="true">
    <proxy usesystemdefault="False" 

    proxyaddress="http://127.0.0.1:8888" 

	bypassonlocal="False" autoDetect="False" />
  </defaultProxy>
</system.net>

Fiddler result without compression

Ways to Apply Data Compression

  1. Using ASP.NET code
  2. Using IIS

Using ASP.NET Code in MVC

To implement this in ASP.NET MVC, we can utilize ActionFilterAttribute and override either OnActionExecuting or OnResultExecuting method.

The below code snippet is being used to check whether the current request browser can accept GZIP/DEFLATE encoding by looking at Accept-Encoding request header. If it finds GZIP encoding in this header, then we would set gzip in Content-encoding in response header and if it supports DEFLATE, then this code would set deflate in Content-encoding.

using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HTTPCompression.ActionFilters
{
    public class CompressAttribute : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding)) return;

            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);
            }
        }
    }
}

Apply this filter attribute to any action wherever you want to apply compression. In my case, I am applying it to About page of default MVC application.

[Compress]
public ActionResult About()
{
    ViewBag.Message = "Your application description page.";

    return View();
}

Now, run the application from IIS and click on About menu from browser to access this page. Go back to the Fiddler and monitor Inspectors of this page request. You would find the compressed text and content-Encoding: gzip in raw text tab.

Image 2

Using IIS

Before enabling data compression in IIS, we need to install Dynamic Compression module from the Server Manager Add Role and Feature.

Install Dynamic Compression Module

Below are few steps to install this module or you can follow this article that explains more in detail.

  1. Click Start | Administrative Tools | Server Manager.
  2. On the left-hand side, expand Roles and then click on Web Server (IIS).
  3. Scroll down to the Role Services section and then click on Add Role Services. The Add Role Services wizard opens:
  4. On the Select Role Services page, scroll down to the Performance section and select Dynamic Content Compression. Click on Next.
  5. Read the message and click Install.
  6. Once the installation is done, close the wizard.

Enable Compression in IIS

Levels

The procedures for configuring HTTP compression can be performed at the following levels in IIS:

  • Web Server
  • Site
  • Application
  • Physical and virtual directories
  • File (URL)

Steps

  1. Open IIS Manager and navigate to the level you want to manage. For information about opening IIS Manager, see Open IIS Manager (IIS 7). For information about navigating to locations in the UI, see Navigation in IIS Manager (IIS 7).
  2. In Features View, double-click Compression.
  3. On the Compression page, select the box next to Enable dynamic content compression.
  4. Click Apply in the Actions pane.

Conclusion

Both approaches have their own advantages and disadvantages. Enabling Data Compression from IIS is very easy to configure and use but you don't always have access to the IIS server to configure it, whereas enabling it from your ASP.NET code would give you a control on Action level data compression.

Compression of dynamic application responses can affect CPU resources because IIS does not cache compressed versions of dynamic output. If compression is enabled for dynamic responses and IIS receives a request for a file that contains dynamic content, the response that IIS sends is compressed every time it is requested. Because dynamic compression consumes significant CPU time and memory resources, use it only on servers that have slow network connections but that have CPU time to spare.

Unlike dynamic responses, compressed static responses can be cached without degrading CPU resources.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

No Biography provided

Comments and Discussions

 
QuestionMethods in ActionFilterAttribute. Pin
Member 1342335120-Dec-17 0:28
MemberMember 1342335120-Dec-17 0:28 
Questionresponse.Filter is null Pin
Robert Cieloszczyk25-Apr-17 3:36
MemberRobert Cieloszczyk25-Apr-17 3:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Tip/Trick
Posted 27 Feb 2016

Stats

33.3K views
281 downloads
14 bookmarked