β‘ 70% Smaller Responses, Same Content
JSON responses are text. Text compresses well. Response compression GZIPs responses automatically. Faster downloads, less bandwidth.
π Enable Compression
// Program.cs
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add();
options.Providers.Add();
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/json", "text/plain" }
);
});
builder.Services.Configure(options =>
{
options.Level = CompressionLevel.Optimal; // Fastest, Optimal, NoCompression
});
var app = builder.Build();
app.UseResponseCompression();
// Now all responses are compressed automatically
π― Verify Compression
// Check response headers
// Content-Encoding: gzip
// Vary: Accept-Encoding
// Curl test
curl -H "Accept-Encoding: gzip" https://localhost:5001/api/data --compressed
// Browser DevTools β Network tab
// Response headers show Content-Encoding: gzip
// Size column shows compressed size vs original
// Disable compression for specific endpoint
[HttpGet, SkipStatusCodePages]
public IActionResult Get()
{
HttpContext.Features.Get()?.Disable();
return Ok(data);
}
π‘ Benefits
- Text responses compress 60-80% (HTML, CSS, JS, JSON, XML)
- Images and binaries already compressed (no benefit)
- Works with CDNs (they respect Vary header)
- Reduces bandwidth costs
- Improves load times on slow connections
“API response: 500KB uncompressed, 80KB after GZIP. 84% smaller. Mobile users on 4G saw 2x faster load times. Essential optimization for public APIs.”
