How to add gzip compression to ASP.NET Core API responses

Cesar Aguirre - Oct 1 '20 - - Dev Community

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();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player