ASP.NET Web API GZip compression ActionFilter with 8 lines of code

If you are building high performance applications that consumes WebAPI, you often need to enable GZip / Deflate compression on Web API.

Compression is an easy way to reduce the size of packages and in the same time increase the speed of communication between client and server.

Two common algorithms used to perform this on the Web are GZip and Deflate. These two algorithms are recognized by all web browsers and all GZip and Deflate HTTP responses are automatically decompressed.

On this picture you can see the benefits of GZip compression.



Source : Effects of GZip compression

How to implement compression on ASP.NET Web API

There are several ways to do this. One is to do it on IIS level. This way all responses from ASP.NET Web API will be compressed.

Another way is to implement custom delegating handler to do this. I have found several examples of how to do this on the internet but it often requires to write a lot of code.

The third way is to implement your own actionFilter which can be used on method level, controller level or for entire WebAPI.


Implement ASP.NET Web API GZip compression ActionFilter

For this example with around 8 lines of code I will use very popular library for Compression / Decompression called DotNetZip library .This library can easily be downloaded from NuGet.

Now we implement  Deflate compression ActionFilter.

 public class DeflateCompressionAttribute : ActionFilterAttribute

    public override void OnActionExecuted(HttpActionExecutedContext actContext)
        var content = actContext.Response.Content;
        var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
        var zlibbedContent = bytes == null ? new byte[0] : 
        actContext.Response.Content = new ByteArrayContent(zlibbedContent);
        actContext.Response.Content.Headers.Add("Content-encoding", "deflate");


We also need a helper class to perform compression.

public class CompressionHelper
        public static byte[] DeflateByte(byte[] str)
            if (str == null)
                return null;

            using (var output = new MemoryStream())
                using (
                    var compressor = new Ionic.Zlib.DeflateStream(
                    output, Ionic.Zlib.CompressionMode.Compress, 
                    compressor.Write(str, 0, str.Length);

                return output.ToArray();


For GZipCompressionAttribute implementation is exactly the same. You only need to call GZipStream instead of DeflateStream in helper method implementation.

If we want to mark some method in controller to be Deflated just put this ActionFilter attribute above method like this :

public class V1Controller : ApiController
    public HttpResponseMessage GetCustomers()




If you find some better way to perform this please let me know.