Thursday, January 14, 2010

Enabling GZip Compression in ASP.NET with AJAX

Compression is a very effective way to make your website faster on the web. There are generally two types of compression GZip and Deflate. You can use any of these methods in your asp.net applications.

Compression can be done by changing the settings in IIS or even at the code level by adding a simple piece of code in your global.asax file.

While implementing GZip compression on my website I came across many solutions but all of them had problem with the AJAX features. However, I have used the following code in my global.asax file, and it works perfectly with all AJAX features.


Private Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim app As HttpApplication = DirectCast(sender, HttpApplication)
        Dim acceptEncoding As String = app.Request.Headers("Accept-Encoding")
        Dim prevUncompressedStream As IO.Stream = app.Response.Filter
    
If acceptEncoding Is Nothing OrElse acceptEncoding.Length = 0 Then
            Return
        End If
    
        If (Request.Path.EndsWith("axd")) Then
            Return
        End If
        
        acceptEncoding = acceptEncoding.ToLower()
    
        If acceptEncoding.Contains("gzip") Then
            ' gzip
            app.Response.Filter = New IO.Compression.GZipStream(prevUncompressedStream, IO.Compression.CompressionMode.Compress)
            app.Response.AppendHeader("Content-Encoding", "gzip")
        ElseIf acceptEncoding.Contains("deflate") Then
            ' defalte
            app.Response.Filter = New IO.Compression.DeflateStream(prevUncompressedStream, IO.Compression.CompressionMode.Compress)
            app.Response.AppendHeader("Content-Encoding", "deflate")
        End If
    End Sub


In the above code, the following lines are the ones that solve the ajax related issues:




        If (Request.Path.EndsWith("axd")) Then
            Return
        End If



Do let me know if this code works for you.