Geeks With Blogs
Amit's Blog Sharing Thoughts and Learning

In this post, I will show you how to compress the Asp.net Ajax Web Service response, To understand the benefits of compression let us start with a simple example, Consider you have an web service which returns a large data like the following:

[WebMethod()]
public string GetLargeData()
{
    using (StreamReader sr = File.OpenText(Server.MapPath("~/DataFile.txt")))
    {
        return sr.ReadToEnd();
    }
}

The web method reads an large text file (around 100KB) and returns it contents. Once we call this method from a page the network activity in the firebug shows like the following:

Plain

Now, lets examine the HttpModule which compress the Ajax Web Service response. The following shows the complete code of this module:

using System;
using System.IO;
using System.IO.Compression;
using System.Globalization;
using System.Web;


public class JsonCompressionModule : IHttpModule
{
    public JsonCompressionModule()
    {
    }

    public void Dispose()
    {
    }

    public void Init(HttpApplication app)
    {
        app.PreRequestHandlerExecute += new EventHandler(Compress);
    }

    private void Compress(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;
        HttpRequest request = app.Request;
        HttpResponse response = app.Response;

        //Ajax Web Service request is always starts with application/json
        if (request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json"))
        {
            //User may be using an older version of IE which does not support compression, so skip those
            if (!((request.Browser.IsBrowser("IE")) && (request.Browser.MajorVersion <= 6)))
            {
                string acceptEncoding = request.Headers["Accept-Encoding"];

                if (!string.IsNullOrEmpty(acceptEncoding))
                {
                    acceptEncoding = acceptEncoding.ToLower(CultureInfo.InvariantCulture);

                    if (acceptEncoding.Contains("gzip"))
                    {
                        response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                        response.AddHeader("Content-encoding", "gzip");
                    }
                    else if (acceptEncoding.Contains("deflate"))
                    {
                        response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                        response.AddHeader("Content-encoding", "deflate");
                    }
                }
            }
        }
    }
}

Next, register this module in the web.config like the following:

<httpModules>
    <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    <add name="JsonCompressionModule" type="JsonCompressionModule"/>
</httpModules>

This time the network activity shows like the following:

Compressed Json

So by adding this little module, we have saved 74KB. Now consider the impact of this in an highly traffic ajax web application :-). You will find the complete source code in the bottom of this post. If you want to learn more optimization tips check out my previous post Implement Yahoo's YSlow in your Asp.net pages and Combine Multiple JavaScript and CSS Files and Remove Overheads.

Download: Full Source

kick it on DotNetKicks.com

Posted on Saturday, September 15, 2007 6:09 AM Asp.net Ajax , Tips/Tricks , Web Service | Back to top


Comments on this post: Compress Asp.net Ajax Web Service Response - Save Bandwidth

# re: Compress Asp.net Ajax Web Service Response - Save Bandwidth
Requesting Gravatar...
Can't you just use IIS's (Ver 6 an above) built-in compression so that you don't have to go through another layer of HttpModule, no? You can just add .axd in the Metabase.xml and it should work.
Left by Rachit on Sep 17, 2007 8:38 AM

# re: Compress Asp.net Ajax Web Service Response - Save Bandwidth
Requesting Gravatar...
Certainly, the built-in compression would do, but how about you are hosting it in a shared hosting environment where you do not have the permission of access the IIS settings?
Left by Kazi Manzur Rashid on Sep 17, 2007 2:34 PM

# re: Compress Asp.net Ajax Web Service Response - Save Bandwidth
Requesting Gravatar...
What application do you use to see the amount of traffic through webservice?
How does the compressed response get decompressed on client side?
Left by Victor on Sep 19, 2007 1:41 AM

# re: Compress Asp.net Ajax Web Service Response - Save Bandwidth
Requesting Gravatar...
I am using the popular FireBug(http://www.getfirebug.com/). The Modern browsers has the support to automatically decompress the response.
Left by Kazi Manzur Rashid on Sep 19, 2007 5:00 AM

# re: Compress Asp.net Ajax Web Service Response - Save Bandwidth
Requesting Gravatar...
thanx man
Left by Articles on Mar 05, 2008 3:58 AM

# re: Compress Asp.net Ajax Web Service Response - Save Bandwidth
Requesting Gravatar...
I've implemented something similar to this, but found that it doesn't work if the server side method throws an exception. The Content-Encoding header somehow gets dropped, so the client isn't able to read the response. That causes the failure callback on the client to never get invoked.

Any idea of a workaround for that?
Left by Brian R on May 07, 2008 5:22 AM

Your comment:
 (will show your gravatar)


Copyright © Kazi Manzur Rashid | Powered by: GeeksWithBlogs.net | Join free