Enabling GZip and Deflate compression from ASP.NET code

Compress your response on hosts where IIS compression is not supported

HTTP compression is a simple way to improve site performance and decrease bandwidth, with no configuration required on the client side. If you test your website through Google PageSpeed Insights, HTTP compression will be one of the points recommended to be used to increase website performance.

Luckily for .NET developers IIS supports it out of the box. All you need to do is to enable it in IIS Manager (https://docs.microsoft.com/en-us/iis/configuration/system.webserver/httpcompression/)

However, if your website is running on a shared host, you will probably not be able to use this feature of IIS as they are probably switched off for you. The reason for this might be a slightly higher CPU usage for additional compression of each request.

The thing is that you can enable this through code with just a few lines.

All you need is HttpModule that will intercept your request and compress it before it is sent back to browser.

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Web;
namespace Custom.Modules
{
public class CompressionModule:IHttpModule
{
public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += context_PreRequestHandlerExecute;
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
string acceptEncoding = app.Request.Headers["Accept-Encoding"];
Stream prevUncompressedStream = app.Response.Filter;
string contentType = app.Context.Response.ContentType;
if (app.Context.Request.HttpMethod == "GET" &&
contentType.Equals("text/html") &&
app.Context.Response.StatusCode == 200 &&
app.Context.CurrentHandler != null
        )
            {
                if (acceptEncoding == null || acceptEncoding.Length == 0)
                    return;

                acceptEncoding = acceptEncoding.ToLower();

                if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
                {
                    // deflate
                    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");
                }
            }
        }
		
		public void Dispose()
        {
			//Noo need to do anything
        }
    }
}

    

In case both Deflate and GZip are supported, Deflate will be taken as default as it is considered faster one. In case you prefer GZip, just change order of conditions in code above and re-deploy your HttpModule library to website.

When you deploy your HttpModule dll, all you need to do is to reference it in web.config and it will work.

<system.webServer>
	<modules runAllManagedModulesForAllRequests="true">
		<remove name="CompressionModule"/>
		<add name="CompressionModule" type="Custom.Modules.CompressionModule"/>
	</modules>
<system.webServer>
    

For testing whether it works you can go to Google PageSpeed Insights page and check your website URL. Additionaly,if you decide to use GZip compression you ccan check at https://checkgzipcompression.com

 

References

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.


About the author

DEJAN STOJANOVIC

Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform including ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus

JavaScript

read more

SQL/T-SQL

read more

Umbraco CMS

read more

PowerShell

read more

Comments for this article