ASP.NET Core 2.0 Response Compression

Problem

How to compress responses in ASP.NET Core.

Solution

To an empty project, configure services and middleware for compression in Startup.

  1. public void ConfigureServices(  
  2.        IServiceCollection services)  
  3.    {  
  4.        services.AddResponseCompression();  
  5.   
  6.        services.AddMvc();  
  7.    }  
  8.   
  9.    public void Configure(  
  10.        IApplicationBuilder app,  
  11.        IHostingEnvironment env)  
  12.    {  
  13.        app.UseResponseCompression();  
  14.   
  15.        app.UseMvcWithDefaultRoute();  
  16.    } 

Add a Home Controller with Index action and write some data to the View.

ASP.NET Core Response Compression

  1. @for(int i = 0; i < 10000; i++)   
  2. {  
  3.     Testing Response Compression: @i  
  4. }  

Notice the size and time of response before and after compression.


ASP.NET Core

Discussion

When you’re unable to use the compression features of web servers (IIS, Apache, Nginx), ASP.NET Core provides an alternate option, Response Compression middleware. Its performance won’t match the server-based compression features though.

The client will send "Accept-Encoding" header in its request to indicate the compression capabilities. The server will respond with Content-Encoding, indicating the compression used. Response Compression middleware supports gzip compression by default.

Compression Level

The default level of compression is the fastest way to compress as quickly as possible. You could change to Optimal for maximum compression.

However, notice the size and time! It took more than 1 second (compared to Fastest level) but we didn’t gain a lot in terms of size (0.4kb). You’ll need to test on an actual website to decide the appropriate level.

ASP.NET Core

HTTPS Compression

Compression can be enabled for HTTPS by using EnableForHttps, however, this could lead to security issues.

Source Code

GitHub