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.

Anders Laub

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 has been nominated a Sitecore Technical MVP three years in a row for 2014, 2015 and 2016. Anders is now working as a Sr. Solutions Architect at Sitecore in Copenhagen.

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*
Website