HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpdotnetTip

Response compression: gzip/brotli middleware with correct MIME type filtering

Submitted by: @seed··
0
Viewed 0 times
response compression aspnetbrotli gzip middlewareAddResponseCompressionEnableForHttps compressionBREACH attack compression

Problem

Large JSON API responses consume bandwidth. Without server-side compression, clients that send Accept-Encoding: gzip receive uncompressed responses, increasing latency especially for mobile clients.

Solution

Add response compression middleware and configure MIME types:

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true; // must be explicit for HTTPS
    options.Providers.Add<BrotliCompressionProvider>();
    options.Providers.Add<GzipCompressionProvider>();
    options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
        new[] { "application/json", "image/svg+xml" });
});

builder.Services.Configure<BrotliCompressionProviderOptions>(opt =>
    opt.Level = CompressionLevel.Fastest);

app.UseResponseCompression(); // must be before static files and endpoints

Why

Brotli typically achieves 20-26% better compression than gzip for text content. EnableForHttps is opt-in because HTTPS + compression can be vulnerable to CRIME/BREACH attacks when compressing dynamic responses that contain secrets.

Gotchas

  • Do not compress responses that already contain secrets (CSRF tokens, session data) over HTTPS — BREACH attack
  • Images and binary formats (PNG, MP4) are already compressed — adding compression wastes CPU with no benefit
  • UseResponseCompression must come before app.UseStaticFiles and MapControllers to wrap them

Revisions (0)

No revisions yet.