ASP.NET - Response Compression Techniques
Response compression reduces the size of data sent from the server to the client. Instead of sending full-size text responses, the server compresses them, which makes pages load faster and reduces bandwidth usage. This is especially useful for APIs and web apps that send large JSON or HTML responses.
Why Compression Improves Performance
Smaller responses travel faster over the network. Compression reduces download time, improves page speed and lowers data transfer costs. Users on slow networks benefit the most because less data needs to be downloaded to display the same content.
How Compression Works
The browser sends a header indicating which compression formats it supports, such as gzip or Brotli. The server selects a supported format, compresses the response and sends it back. The browser automatically decompresses the response before using it, so users do not notice any difference in behavior.
Common Compression Methods
Gzip is widely supported and commonly used. Brotli provides better compression ratios and is preferred when supported by the browser. ASP.NET Core can enable both and automatically choose the best option based on the request headers.
What Should Be Compressed
Text-based responses such as JSON, HTML, CSS and JavaScript benefit most from compression. Images and videos are usually already compressed, so applying compression again gives little benefit and may waste CPU resources.
Why Proper Configuration Matters
Compression uses CPU power. Applying it only to suitable content types ensures better performance. Correct configuration balances speed and server resource usage, especially in high-traffic applications.
Example
var builder = WebApplication.CreateBuilder(args);
// Add response compression
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
});
var app = builder.Build();
// Enable compression middleware
app.UseResponseCompression();
app.MapGet("/data", () =>
{
return new string('A', 5000); // large text response
});
app.Run();
Result
The /data endpoint sends a compressed response to supported browsers, reducing size and improving load speed.