⚙️ Asp.Net Core: Fix Response Compression Skipping a Streamed Result
The built-in Response Compression middleware decides whether to compress a response largely by checking the Content-Length header up front, and a result written via IAsyncEnumerable<T> or a manually streamed Stream response typically never sets that header at all, since the total size isn’t known in advance. Compression middleware configured with its defaults silently skips these responses entirely, leaving large streamed payloads uncompressed even though smaller, fully-buffered JSON responses right next to them compress just fine.
🔎 The Problem
app.UseResponseCompression();
app.MapGet("/export", async (HttpContext ctx) => {
ctx.Response.ContentType = "application/json";
// no Content-Length set - it's a live stream
await foreach (var row in GetRowsAsync())
await JsonSerializer.SerializeAsync(ctx.Response.Body, row);
});
// Response-Encoding header: absent. Payload: fully uncompressed.
✅ Fix: Make Compression Explicit for Streamed Endpoints
- Register the response’s content type explicitly with
options.MimeTypesinAddResponseCompression()and confirm it actually matches the streamed endpoint’s realContent-Type, since an unmatched or missing MIME type is a separate, common reason compression gets skipped. - For endpoints where streaming is specifically for memory efficiency on huge payloads, wrap the response body in a
GZipStreammanually and setContent-Encoding: gzipyourself, rather than relying on the generic middleware’s content-length-based heuristics. - Verify with a raw
curl -i --compressedrequest against the endpoint directly — browser DevTools sometimes hide the real wire-level headers, and this is the fastest way to confirm whether compression is actually happening.
🚨 Why This Is Dangerous
- A reporting endpoint that silently ships uncompressed instead of the 70-80% smaller payload everyone assumed response compression was providing can quietly inflate bandwidth costs and slow down every client on a metered or slow connection, with nothing in the logs flagging it as a regression.
Response compression isn’t a universal safety net — it only catches what it was configured to recognize, and a stream with no declared length is easy to miss entirely.





