Response Compression in .NET Core

Introduction

The HTTP protocol is used to carry out this compression. The server can compress the data using techniques like Gzip, Deflate, or Brotli. These methods are supported by browsers, which can also extract the compressed data and transform it back into the original format.

App responses can be compressed to reduce payload sizes and expedite data transmission.

Compression with HTTPS

  • The EnableForHttps option controls compressed responses over secure connections.
  • Because dynamically created pages pose security hazards, this feature is disabled by default.
  • ASP.NET Core uses anti-forgery tokens to combat BREACH and CRIME attacks.
  • Keep in mind that even with EnableForHttps disabled, gzip may still be applied at the IIS web server by IIS, IIS Express, and Azure App Service.

When to Use Response Compression Middleware?

  • When feasible, make use of server-based response compression technologies (such as IIS, Apache, and Nginx).
  • Server modules may outperform the response compression middleware in terms of performance.
  • At the moment, neither the Kestrel nor the HTTP.sys servers allow compression by default.

Client and server interaction

  • Clients must deliver the Accept-Encoding header to the server, indicating their capabilities.
  • To specify how the compressed answer is encoded, servers add information in the Content-Encoding header.
  • Gzip and Brotli are supported content encoding designations.

Configure response compression in ASP.NET Core

  • We need to register the response compression method in our Program.cs file.
  • It’s already a built-in method available, so we can use that method at registration time.
    builder.Services.AddResponseCompression();
  • Another approach is there; please refer to the below steps for that
  • Install Microsoft’s response compression package via NuGet.
  • The package name is Microsoft.AspNetCore.ResponseCompression.

You need to add the following code to the Program.cs file to enable response compression for HTTPS

Keep in mind that no further compression providers will be added automatically after you've installed one. To add them as needed, you'll have to develop your code.

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;
    options.Providers.Add<BrotliCompressionProvider>();
    options.Providers.Add<GzipCompressionProvider>();
    options.MimeTypes = ResponseCompressionDefaults.MimeTypes;
});

Here is the provider configuration added for performance.

builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Fastest;
});
builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Optimal;
});

You should configure the HTTP request pipeline using the following code in order to add the response compression middleware to the request processing pipeline and compress responses dynamically.

app.UseResponseCompression();

Let’s check how much we are compressing the response.

We need to create one sample application, and in that, we can create the API controller.

We are creating the endpoint, and inside that, we can create the dummy response for verification purposes.

API endpoint code

Here is the API endpoint code

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        var employees = new List<Employee>();

        for (int i = 0; i < 10000; i++)
        {
            employees.Add(new Employee
            {
                EmpId = Guid.NewGuid(),
                Name = $"Employee Name {i}",
                Address = $"Employee Address {i}",
            });
        }

        return Ok(new { employees });
    }
}

In the above example, I have created 10,000 employees and returned those employees to the API response.

Let's verify first without adding the compression to the API response.

Values

Name

When I was executing the API without compression, the response size was 1.1 MB.

Let's verify adding the compression to the API response.

API response

When I was executing the API with compression, the response size was 298kb.

Creating the custom compression provider

If you want to create a custom compression provider to compress and decompress the API response, then we can do it in the .Net core application.

As demonstrated below, the first step in creating a custom compression provider is to construct a class that implements the ICompressionProvider interface.

public class CustomCompressionProvider : ICompressionProvider
{
    public Stream CreateStream(Stream stream)
    {
        // Write your code here to compress the data
        return stream;
    }
}

Once you have done your custom compression provider, we need to register this custom compression provider in the Program.cs file.

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;
    options.Providers.Add<CustomCompressionProvider>();
});

We learned the new technique and evolved together.

Happy coding.


Similar Articles