Skip to content

Gzip Compression with NancyFX

Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.

Learn more about Software Architecture & Design.
Join thousands of developers getting weekly updates to increase your understanding of software architecture and design concepts.


Gzip compressionI was looking at the size of the payloads in my web api and thought it would be worth investigating if adding HTTP compression via gzip would be worthwhile. After a quick search, I found a post by Simon Cropp back from 2011.  This was a good starting point, however how you wired it up with Nancy current day (1.4.3) is a bit different.

Compressing

I’ve basically taken Simon’s code and added it to a new class that implements IApplicationStartup. There are a few checks that occur before compressing the output.
  • Does the incoming request accept header contain gzip?
  • Is the outgoing HTTP status code 200?
  • Is return content type compatible?  In my example, I’m only checking for application/json.
  • Is return content length large enough?
If all are true, then the output is compressed.

Wiring Up

One reason I really love Nancy is how it scans assemblies looking for implementations of interfaces.  This makes it so seamless to add functionality. Adding this class to your project is all you need to do.  Seriously.  This is indeed the super-duper-happy-path. You can also hook into the pipeline via the bootstrapper, I just happened to prefer creating a class that implements the IApplicationStartup as I can easily reuse it by dropping it into other projects.

Results

In my demo project, I’ve added a a json file with generated data.  I’m output this file at the endpoint /nancy/gziptest. Without gzip gzip-off With gzip gzip-on

Source Codegithub-octocat

The source code for this demo is available on GitHub.

NuGet

I’ve created a NuGet Package which has a slighly different implementation as it does not use IApplicationStartup.  It requires you to enable gzip compression in your Bootstrapper with a extension method.  Literally one line of code needed.  You can also view that source code on GitHub.  

4 thoughts on “Gzip Compression with NancyFX”

  1. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #2025

  2. Pingback: ASP.NET Core Embedded Resource - CodeOpinion

Leave a Reply

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