How to use Response Compression Middleware in ASP.NET Core

Programming, error messages and sample code > ASP.NET
Reducing the size of the response usually increases the responsiveness of an app, often dramatically. One way to reduce payload sizes is to compress an app's responses.

When to use Response Compression Middleware

Use Response Compression Middleware when the app is not using the IIS Dynamic Compression module.

Configuration

The following code shows how to enable the Response Compression Middleware for default MIME types and compression providers (Brotli and Gzip):
 
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;
});

var app = builder.Build();

app.UseResponseCompression();

app.MapGet("/", () => "Hello World!");

app.Run();
Notes:
  • Setting EnableForHttps to true is a security risk. See Compression with HTTPS for more information.
  • app.UseResponseCompression must be called before any middleware that compresses responses. For more information, see ASP.NET Core Middleware.
  • Use a tool such as Postman to set the Accept-Encoding request header and examine the response headers, size, and body.