I originally posted an extended version of this post on my blog.
To compress responses with ASP.NET Core, register the default compression providers into the dependencies container with the UseResponseCompression()
method.
Something like this,
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddResponseCompression(); // ๐
var app = builder.Build();
app.UseResponseCompression(); // ๐
app.MapControllers();
app.Run();
If we don't specify any compression provider, ASP.NET Core uses a default one.
If we want gzip compression, then let's register the GzipCompressionProvider
inside AddResponseCompression()
and set its compression level by configuring the GzipCompressionProviderOptions
,
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddResponseCompression(options =>
{
options.Providers.Add<GzipCompressionProvider>(); // ๐
});
builder.services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest; // ๐
});
var app = builder.Build();
app.UseResponseCompression(); // ๐
app.MapControllers();
app.Run();
In previous versions of ASP.NET Core, we needed the Microsoft.AspNetCore.ResponseCompression
NuGet package. It's deprecated now. ASP.NET Core has response compression built in now. We don't need NuGet packages for this.
Source: Response compression in ASP.NET Core
Starting out or already on the software engineering journey? Join my free 7-day email course to refactor your coding career and save years and thousands of dollars' worth of career mistakes.
Happy coding!