ASP.NET Core Response Compression
In this blog post, we show how to make response compression work in ASP.NET Core with the help of Brotli. Read on to get started!
Join the DZone community and get the full member experience.
Join For FreeASP.NET Core supports response compression. From popular algorithms, gzip and Brotli are supported. Those who like can also implement their own response compression providers. This blog post shows how response compression works in ASP.NET Core.
With ASP.NET Core we have three options for compression:
- ASP.NET Core does the compression.
- The ront-end web server does the compression.
- Static files are precompressed.
We can skip the second and third options here because we are interested in how ASP.NET Core carries out response compression. Those who don't use the Microsoft.AspNetCore.App metapackage must add a reference to the Microsoft.AspNetCore.ResponseCompression NuGet package to enable response compression.
Test Page
I'm using a simple test page for this guide. Not much content, not many files, and the effects of compression are easy to see and compare.
By default, without any compression the page loads as shown in the image below.
When read from cache the numbers are different.
I start with a table to visualize the effects of the response compression better.
Let's leave these numbers here for a moment and make the compression work.
gzip
Let's get started with gzip compression as it comes out-of-box. No tricks, no miracles. First we have to set the option for compression and then add the compression to request the middleware pipeline. We do it in the ConfigureServices()
method of the Startup
class.
services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<GzipCompressionProvider>();
});
For HTTPS, we have to say when we want to use compression due to CRIME and BREACH security exploits.
There are three possible values for compression level:
- NoCompression - compression is ignored.
- Optimal - golden way between compression level and CPU resources (default).
- Fastest - compressing with minimal effects on server load.
Next we have to modify the Configure()
method of the Startup
class.
app.UseStaticFiles();
// Enable compression
app.UseResponseCompression();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
BUG! I made one bad mistake in the code above but let's get to it later as it doesn't affect what we are doing right now.
Let's try to load the page with both compession levels. We start with the fastest compression and then try for the optimal compression.
gzip with the fastest compression level
gzip with the optimal compression level
And let's write the results to table.
Compression | Response size (KB) | % |
---|---|---|
No compression | 764.99 | 100.00 |
No compression, from cache | 11.25 | 1.47 |
gzip, fastest | 652.62 | 85.31 |
gzip, optimal | 652.43 | 85.23 |
The numbers are very similar for both compression levels. It should ring an alarm for those readers who have worked with response compression before. But we'll get to that later.
Brotli
Brotli is new open-source compression algorithm supported by almost all major browsers. It provides better compression than gzip. More information about browser support for Brotli is available at Can I Use.
On our application side there's nothing very much different. We already have everything configured and introducing Brotli is easy. We have to configure its options and add Brotli's compression provider to the response compression provider's collection.
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Optimal;
});
services.AddResponseCompression(options =>
{
options.EnableForHttps = true; options.Providers.Add<BrotliCompressionProvider>();
});
With brotli enabled, let’s also create two tests – one with each compression level.
Brotli with the fastest compression level
Brotli with the optimal compression level
Let's add these results to table.
Compression | Response size (KB) | % |
---|---|---|
No compression | 764.99 | 100.00 |
No compression, from cache | 11.25 | 1.47 |
gzip, fastest | 652.62 | 85.31 |
gzip, optimal | 652.43 | 85.23 |
Brotli, fastest | 652.74 | 85.32 |
Brotli, optimal | 651.83 | 85.21 |
The results are almost on the same level as gzip, and this seems weird to me. Why introduce a new compression algorithm if the benefits are so small? Okay, time to confess...
Compressing Static Files
I did great on sweeping some dust under the carpet before and I didn't stop on the closed investigation of static files. Let's run the application and see some static files.
They're not compressed. Why? The question comes down to the request middleware ordering in the application's start-up. We have to put compression before static files in the Configure()
method. Otherwise, the static files' middleware finds a static file and returns it immediately.
// Enable compression
app.UseResponseCompression();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
With static files properly managed, let's run the application again to see the results.
Compression | Response size (KB) | % |
---|---|---|
No compression | 764.99 | 100.00 |
No compression, from cache | 11.25 | 1.47 |
gzip, fastest | 289.92 | 37.90 |
gzip, optimal | 268.92 | 35.15 |
Brotli, fastest | 293.74 | 38.40 |
Brotli, optimal | 252.65 | 33.03 |
When we compare the results, we can see more differences. Brotli with optimal compression is faster and it gives even more effect when the responses used are bigger than the ones I had.
Controlling Compression of Static Files
By default, these MIME-types are compressed:
- application/javascript
- application/json
- application/xml
- text/css
- text/html
- text/json
- text/plain
When configuring response compression, we can specify our own list of types to compress.
services.AddResponseCompression(options =>
{
IEnumerable<string> MimeTypes = new[]
{
// General
"text/plain",
"text/html",
"text/css",
"font/woff2",
"application/javascript",
"image/x-icon",
"image/png"
};
options.EnableForHttps = true;
options.MimeTypes = MimeTypes;
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<BrotliCompressionProvider>();
});
Similar way we can exclude set of MIME-types from compression.
services.AddResponseCompression(options =>
{ IEnumerable<string> MimeTypes = new[]
{
// General
"text/plain",
"text/html",
"text/css",
"font/woff2",
"application/javascript",
"image/x-icon",
"image/png"
};
options.EnableForHttps = true;
options.ExcludedMimeTypes = MimeTypes;
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<BrotliCompressionProvider>();
});
Having a list of allowed types doesn't mean that compression happens. When activated, then compression is use based on the browser's Accept-Encoding header. If this header doesn't specify any known compression algorithm then ASP.NET Core doesn't compress the requested file.
Wrapping Up
Response compression can save us a lot of traffic when applied to a ASP.NET Core web application. Public interface of the response compression API is simple and flexible. We can control compression levels and the MIME-types to be compressed. For static files, we have to include response compression before static files' middleware because otherwise it will not run. And, as we saw, the new Brotli compression is better than the older gzip versoin.
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments