Gzip WebApi Response Content using an attribute

Today I was asked why json responses from WebApi was not being gzipped since it brought down our score on Google Page Speed.

So yet again I started my ongoing fight with Google Page Speed. It turns out that we had issues making IIS gzip application/json data. Since we do not have direct access to the production environment I decided that we would be better off simply gzipping the response content in code where and when we wanted to.

So I thought there must be an ActionFilterAttribute for this already but it turns out there is not.

I searched and searched and came by this fine solution which adds a MessageHandler that gzips responses.

But I would so much prefer just to be able to mark a method or a controller class with an attribute, that just seems cleaner.

So I decided to write the following ActionFilterAttribute :

Where CompressedContent is a class that derives from HttpContent highly inspired by the post I referenced above.

And now we can use the CompressFilter attribute on classes like this:

Or on methods like this:

When to use it?

It is best to let IIS perform the compression instead of doing it in code.

But if this for some reason is not possible to configure or if you for some reason only want selected responses to be gzipped then this attribute will do the job just perfect.

There is also a fine line for when it makes sense to let the server use time on gzipping the response. This is why IIS has an optional config attribute on the httpCompression element for setting a minimum file size before compression (minFileSizeForComp).

Hope this helps someone out there.

Avatar photo

Anders Laub Christoffersen

Anders has been working with Sitecore for over a decade and has in this time been the lead developer and architect on several large scale enterprise solutions all around the world. Anders was appointed the title of Sitecore Technical MVP in 2014 and has been re-appointed the title every year since then.