This guide offers a comprehensive walkthrough of response compression in ASP.NET Core. It begins with fundamental concepts such as network bandwidth and middleware in ASP.NET Core. It then explores what response compression is, when to use response compression middleware, compression providers, middleware setup, and ultimately the results of response compression middleware. By the end of this guide, you will have a thorough understanding of the topic.
Let’s dive in!
Network bandwidth
Bandwidth refers to the maximum amount of data that can be transmitted over a network connection, whether wired or wireless, within a specific time frame. It is measured in bits (B), kilobits (KB), megabits (MB), or gigabits (GB) per second. Since bandwidth is a limited resource, it’s important to manage it effectively. For instance, a network bandwidth of 1 Mbps means that 1 million bits can be transferred every second. If more data is sent than the network can handle, it may lead to congestion, resulting in decreased performance. Therefore, smaller response sizes can be transmitted more quickly, which in turn enhances overall application performance.
Middleware in ASP.NET Core
The middleware component is added to the application pipeline to manage incoming requests and outgoing responses. The response compression middleware has been available since ASP.NET Core 1.1.
Response Compression
The client includes the “Accept-Encoding” header in its request, while the server responds with a “Content-Encoding” header that indicates how the response in encoded. It is important to note that applying additional compression to files that are already compressed, such as CSS and HTML, may result in larger file sizes.
When to use Response Compression Middleware:
Servers such as IIS and Nginx come with built-in response compression modules, while HTTP.sys and Kestrel servers do not have this feature. When an application is hosted on a server that lacks built-in response compression, response compression middleware is used. However, it’s important to note that the performance of response compression middleware tends to be the least efficient compared to server modules.
Compression with HTTPS
The EnableForHttps option controls compression over secure connections. It is susceptible to CRIME and BREACH attack risks when EnableForHttps is set to true.
Compression Providers
There are two available compression providers: Brotli and Gzip. The default compression provider is determined by the data format supported by the client. For example, if the client supports the Brotli compressed data format, the default compression will be set to Brotli. If the client does not support Brotli but does support Gzip, then Gzip will be used as the default compression method. Compression level can also be configured. Brotli is the default compression provider. For the Brotli compression provider, you can set the compression level using the BrotliCompressionProviderOptions. Similarly, for the Gzip compression provider, use GzipCompressionProviderOptions. There are four levels of compression available, and you can choose the appropriate CompressionLevelEnum value based on your specific needs, whether you prioritize speed or size. The available levels are:
- Optimal
- Fastest
- NoCompression
- SmallestSize
Middleware Setup
The code below is from the Program.cs file in a .NET 8 minimal web API project. I added the comments in the code for clarity.
//.net 8 minimal web api //Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// configure the services for response compression
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
// when you want to configure a custom compression provider
//options.Providers.Add<CustomCompressionProvider>(); });
//when brotli compression provider is used then the priority is the fastest.
builder.Services.Configure<BrotliCompressionProviderOptions>(options => { options.Level = CompressionLevel.Fastest; });
//when gzip compression provider is used then the priority is the size.
builder.Services.Configure<GzipCompressionProviderOptions>(options => { options.Level = CompressionLevel.SmallestSize; });
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger(); app.UseSwaggerUI();
}
// add the response compression middleware to the request pipeline
// must be called before any middleware that compresses responses
app.UseResponseCompression();
var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
app.MapGet("/weatherforecast", () => {
var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast
( DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55), summaries[Random.Shared.Next(summaries.Length)] )) .ToArray(); return forecast;
}) .WithName("GetWeatherForecast");
app.Run();
internal record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
// CustomCompressionProvider.cs
public class CustomCompressionProvider : ICompressionProvider
{
public Stream CreateStream(Stream data) { return data; }
}
Results and Conclusion
Below is a table comparing the compressed size and time based on two compression providers (Brotli, Gzip) and three compression levels (Fastest, Smallest Size, Optimal).
Response compression middleware plays a crucial role in reducing bandwidth requirements and improving the responsiveness of an application. However, it can sometimes have negative effects if the chosen compression provider or the level of compression does not meet your specific needs. Therefore, it’s important to exercise caution when using response compression middleware to ensure it aligns with your application’s requirements.
No Compression
436 B
6 ms
------------------------------------------------------------------------------------------------------------------------------------------------------
Brotli
Fastest
287 B
67 ms
SmallestSize
241 B
43 ms
Optimal
246 B
45 ms
------------------------------------------------------------------------------------------------------------------------------------------------------
Gzip
Fastest
289 B
50 ms
SmallestSize
289 B
50 ms
Optimal
290 B
33 ms
Screenshots
Request Header:
Response Header:
NoCompression Response Details: