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.
But if you're still using ASP.NET Core 2.x, here you go,
public void ConfigureServices(IServiceCollection services)
{
services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
services.AddResponseCompression(options =>
{
options.Providers.Add<GzipCompressionProvider>();
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseResponseCompression();
}
Source: Response compression in ASP.NET Core
Hey, there! I'm Cesar, a software engineer and lifelong learner. Visit my Gumroad page to download my ebooks and check my courses.
Happy coding!