Usage of response compression in ASP.NET Core 1.1

By Dawid on (tags: compression, middleware, .NET Core 1.1, response, categories: code)

When you’ve limited network bandwidth or you are unable to use the Dynamic Compression module in IIS then ASP.NET Core 1.1 comes with rescue. ASP.NET Core team provides a middleware to handle response compression. All modern browsers support multiple compression schemes such as deflate and gzip. Using this feature in your web application can improve overall user experience.


Package and Configuration

To start using middleware in your project simply add reference to the Microsoft.AspNetCore.ResponseCompression and modify your Startup.cs class as show bellow:

Following code will enable Response Compression Middleware with default Gzip compression and for default MIME types. With small modification of above code we can configure default GzipCompressionProvider and set compression level for one of those:

  • CompressionLevel.Fastest – use this if you want to have compression as quick as possible – even if the output might not be optimally compressed
  • CompressionLevel.NoCompression – no compression at all
  • CompressionLevel.Optimal – optimal compression of the output even if it will take slightly more time

Extending list of MIME types

The middleware identifies the compressible resources by their mime types. By default, only text, html, css, js and json files are compressed. But it’s quite easy to extend list of supported MIME types like that:

Performance

Middleware is about 25-30% slower then IIS compression. What is more on IIS (or nginx) has a threshold for compression to avoid compressing very small files. In general you shouldn't compress files smaller than about 150-1000 bytes as this may produce a compressed file larger than the file itself.

Summary

In most of cases it’s very important to reduce size of pages and by that reduce load times. With this middleware it’s easily achievable with just two lines of code. On the other hand if performance is more important for you then you should use the response compression provided by IIS or nginx.

Don't forget to validate (Fiddler or developer console) that all compressible pages and resources are really compressed!