Home  »  Articles  »  ASP.Net  »

Speed up your ASP.Net website by using HTTP compression

 Posted By : Manoranjan SahooPosted Date : 22/07/2011 10:56:12 AM Category : ASP.Net Points : 8 (Rs 2.00)

Page loading speed is very important thing for any website. If your website takes too much time to load webpage then it may affects your user. So, you need to speed up your page loading. There are several techniques available to speed up the site. HTTP compression is one of the technique. There are two types of compression available in .Net. i.e. :

  • GZip
  • deflate

By using above two compression technique you can speed up your asp.net website.

Compression can be performed in two stages. i.e. IIS level or Web Site level. If you enable in IIS level then it will reflect to all website hosted on that IIS. if you want to setup IIS level compression then click here. If you want to do in a single website then you can do by little changes in code. In this article i am going to explain in detail about page level or website level compression.

How to do HTTP Compression?

To accomplish this, We need to compress the response output. It can be easily done by DeflateStream or GzipStream classes.  These two classes available in System.IO.Compression  namespace. Between these two deflate is the more fast than Gzip. Because Gzip contains more header info than deflate. To use HTTP compression in our ASP.NET website without editing each and every single page, we will use ASP.NET web application's life cycle events in Global.asax file.

A Global.asax file is placed in your root folder. There are several methods available in Global.asax file to handle ASP.Net life cycle events. We will handle PreRequestHandlerExecute event to insert our code in this method. This event occurs just before ASP.NET starts executing an event handler.

To do the HTTP  compression follow below steps :

1.  create Global.asax file in the root directory(if there is no Global.asax file).

2. Then make some changes as per the below code.

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>

<script runat="server">

    void Application_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;
        string acceptEncoding = app.Request.Headers["Accept-Encoding"];
        Stream prevUncompressedStream = app.Response.Filter;

        if (!(app.Context.CurrentHandler is Page ||
            app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
            app.Request["HTTP_X_MICROSOFTAJAX"] != null)
            return;

        if (acceptEncoding == null || acceptEncoding.Length == 0)
            return;

        acceptEncoding = acceptEncoding.ToLower();

        if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
        {
            // defalte
            app.Response.Filter = new DeflateStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "deflate");
        }
        else if (acceptEncoding.Contains("gzip"))
        {
            // gzip
            app.Response.Filter = new GZipStream(prevUncompressedStream,
                CompressionMode.Compress);
            app.Response.AppendHeader("Content-Encoding", "gzip");
        }
    }
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

    }
    
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }
        
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.

    }
       
</script>

The above code will enable HTTP compression in your ASP.NET website.

The first thing we do is to tell the ASP.NET compiler that we are using C# language. It means all the below codes are in C# language.

<%@ Application Language="C#" %>

As i said above the DeflateStream and GZipStream classes are available in the System.IO.Compression namespace. So we need to import this namespace.

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>

Next, we need to declare the method which will handle the PreRequestHandlerExecute life cycle event.

void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
	...
}

Then in this method, We need to confirm that the requested ASP.NET resource is either a valid ASP.NET page or a Web Service. If it is not, then we just return and do nothing. we also check for "HTTP_X_MICROSOFTAJAX" item in the HttpRequest collection. This item is present if we are using AJAX in our web site.  because if we use AJAX and then compress the HTTP then it will through an exception.

app.Response.Filter exposes a Stream which we override with a GZipStream object or deflate object, this will cause the raw text response to get compressed, then we need to tell the browser that this response is compressed. So we need to add this to header by  app.Response.AppendHeader.

Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.