How to use response compression in ASP.NET Core
By FoxLearn 12/31/2024 8:01:44 AM 88
How Response Compression Works
Compression works by reducing the size of the data sent from the server to the client. Popular algorithms like Brotli, Gzip, and Deflate are commonly used to achieve this. Most modern web browsers support these algorithms. In ASP.NET Core, the response compression middleware typically uses Brotli or Gzip, depending on what the client supports.
The response compression middleware in ASP.NET Core should only be used if the web server lacks built-in compression or if you're using Kestrel, ASP.NET Core's default server.
Configuring Response Compression in ASP.NET Core
To implement response compression in an ASP.NET Core project, follow these steps:
Start by creating a new ASP.NET Core minimal Web API project in Visual Studio. Choose the "ASP.NET Core Web API" template and ensure you select .NET 7.0 as the framework.
Next, In the NuGet Package Manager, install the Microsoft.AspNetCore.ResponseCompression
package, which adds the necessary functionality for response compression:
Install-Package Microsoft.AspNetCore.ResponseCompression -Version 2.2.0
In the Program.cs
file, configure the compression services and middleware. To enable compression for both HTTP and HTTPS requests:
builder.Services.AddResponseCompression();
If you want to enable compression for HTTPS, add the following:
builder.Services.AddResponseCompression(options => { options.EnableForHttps = true; });
Adding Compression Providers
You can also configure which compression providers (Brotli, Gzip) to use for optimal performance.
builder.Services.AddResponseCompression(options => { options.EnableForHttps = true; options.Providers.Add<BrotliCompressionProvider>(); options.Providers.Add<GzipCompressionProvider>(); });
Configuring Compression Levels
Fine-tune the performance by adjusting the compression levels:
builder.Services.Configure<BrotliCompressionProviderOptions>(options => { options.Level = CompressionLevel.Fastest; }); builder.Services.Configure<GzipCompressionProviderOptions>(options => { options.Level = CompressionLevel.Optimal; });
Adding Middleware to the Pipeline
Finally, ensure the middleware is applied by adding it to the request pipeline:
var app = builder.Build(); app.UseResponseCompression();
Implementing a Custom Compression Provider
If the built-in compression options don't suit your needs, you can create a custom compression provider.
public class CustomCompressionProvider : ICompressionProvider { public Stream CreateStream(Stream outputStream) { // Implement custom compression logic here return outputStream; } }
Then register this custom provider in Program.cs
:
builder.Services.AddResponseCompression(options => { options.Providers.Add<CustomCompressionProvider>(); });
To see the benefits of compression in action, implement a simple controller in your API:
[Produces("application/json")] [Route("api/Products")] public class ProductsController : Controller { [HttpGet] public List<Product> Get() { var products = new List<Product>(); for (int i = 1; i <= 50; i++) { products.Add(new Product { Id = i, Name = $"Product {i}", Description = "This is a sample product description.", Price = Math.Round(new Random().NextDouble() * 100, 2) // Generate a random price }); } return products; } } public class Product { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public double Price { get; set; } }
In this example:
- The
ProductsController
is defined with the routeapi/Products
. - The
Get()
method creates and returns a list of 50Product
objects, each with anId
,Name
,Description
, and a randomly generatedPrice
. - The
Product
class represents the structure of the product data, including properties likeId
,Name
,Description
, andPrice
.
When you enable response compression, the size of the response will decrease significantly.
To disable compression, simply comment out the AddResponseCompression()
and UseResponseCompression()
lines in Program.cs
.
HTTPS Compression Considerations
Be cautious when using response compression over HTTPS, as it may expose your application to security vulnerabilities, such as CRIME and BREACH attacks. These attacks exploit compression to extract sensitive data like credentials or session cookies. To mitigate such risks, it's recommended to use TLS compression instead of relying on HTTPS-level compression.
- Content Negotiation in Web API
- How to fix 'InvalidOperationException: Scheme already exists: Bearer'
- How to fix System.InvalidOperationException: Scheme already exists: Identity.Application
- Add Thread ID to the Log File using Serilog
- Handling Exceptions in .NET Core API with Middleware
- InProcess Hosting in ASP.NET Core
- Limits on ThreadPool.SetMinThreads and SetMaxThreads
- Controlling DateTime Format in JSON Output with JsonSerializerOptions