ASP.NET HTTP Comression and reducing response size

Compression is important on the Web. Pre-compression, my pages were sometimes 700 KB+! Granted, this was in a development environment, so more than half of the page was dedicated to debug and trace data, but still, under high traffic, a large page can put unnecessary strain on your Web server and bandwidth/throughput, thus slowing your site for all of your visitors.

I did a couple of things to drastically reduce the sizes of my pages. First and foremost, I disabled that ASP.NET event validation crap. ASP.NET purists might tell me that I’ve committed a mortal sin, but really… I don’t need it and chances are you don’t need it either. If you’re really that worried, just hit Google and find a pros/cons lists.

You may even be able to turn off the View State, but that broke my pages.

Turning off ASP.NET Event Validation in web.config

<system.web>
    <pages enableEventValidation="false" />
</system.web>

Okay, so now I’ve saved a few precious KB. K. Scott Allen has an article related to Event Validation that goes a bit more in-depth, specifically how to register individual user controls for event validation, and turning off event validation for just one page.

Now the meet and potatoes – here’s how I reduced my overall response size by 52% from an initial 787 KB to 376 KB.

Implementing HTTP gzip/deflate compression in Global.asax (in C#)

void Application_BeginRequest(object sender, EventArgs e)
{
    HttpCompress((HttpApplication)sender);
}

private void HttpCompress(HttpApplication app)
{
    try
    {
        string accept = app.Request.Headers["Accept-Encoding"];
        if (accept != null && accept.Length > 0)
        {
            if (CompressScript(Request.ServerVariables["SCRIPT_NAME"]))
            {
                Stream stream = app.Response.Filter;
                accept = accept.ToLower();
                if (accept.Contains("gzip"))
                {
                    app.Response.Filter = new GZipStream(stream, CompressionMode.Compress);
                    app.Response.AppendHeader("Content-Encoding", "gzip");
                }
                else if (accept.Contains("deflate"))
                {
                    app.Response.Filter = new DeflateStream(stream, CompressionMode.Compress);
                    app.Response.AppendHeader("Content-Encoding", "deflate");
                }
            }
        }
    }
    catch (Exception ex)
    {
        //handle the exception
    }
}

private bool CompressScript(string scriptName)
{
    if (scriptName.ToLower().Contains(".aspx")) return true;
    if (scriptName.ToLower().Contains(".axd")) return false;
    if (scriptName.ToLower().Contains(".js")) return false;
    return true;
}

What we’ve done here is we’ve wrapped the response in a Response.Filter object, which lets us manipulate the response before sending it back to the browser. Careful – there are is a known issue when using Server.Transfer with HTTP Filters.

The bit where we prevent compression of a couple file extentions (see CompressScript(string scriptName)) is important, because ASP.NET doesn’t like it when you compress WebResource.axd, since that’s the file that contains the JavaScript postback code.

That’s pretty simple code to reduce the size of your response by over 50%. I usually implement this with a config setting in web.config that allows me to easily turn on/off the compression just in case breaks something. You could even take that a step further and turn it off on a per page level by looking at HttpContext.Current.Request.Url.

6 Comments

  1. eanirudh
    Posted November 3, 2008 at 11:20 am | Permalink

    good work. very professional code

  2. Posted July 24, 2012 at 4:01 pm | Permalink

    Have you ever considered about adding a little bit more than just your
    articles? I mean, what you say is valuable and all. But think about if you
    added some great images or video clips to give your
    posts more, “pop”! Your content is excellent but with pics and video
    clips, this blog could definitely be one of the best in its
    niche. Terrific blog!

  3. Posted July 25, 2012 at 7:20 pm | Permalink

    I pay a visit daily a few web pages and blogs
    to read posts, however this web site provides feature based
    content.

  4. Posted July 31, 2012 at 10:08 am | Permalink

    What makes a good school? However, there exists a fundamental distinction between your two that makes their outcomes not the same as each other – the designer as well as the
    stager’s end goal.

  5. amis
    Posted October 16, 2013 at 12:37 pm | Permalink

    This causes buttons that postback inside update panel to not redirect to other page, is it possible to solve this?

  6. Posted July 27, 2014 at 12:23 pm | Permalink

    I would have to surprise a lot of music veterans and go with Fruity Loops Studio for my
    third choice. Make sure that you are working
    in a quiet environment. It is an easy task to facilitate online surveys
    by making use of online survey software therefore a lot of
    online businesses consider them all the time.


Post a Comment

Required fields are marked *

*
*

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: