In ASP.NET Core, what does UseRequestDecompression do with a gzip-encoded request body, and how does it protect the app from decompression bombs?
answer
- AddRequestDecompression + UseRequestDecompression
- br, deflate, gzip by Content-Encoding
- header removed, body wrapped
- unknown or multiple encodings pass through
- decompressed size vs MaxRequestBodySize: 413
basics
~20 sUseRequestDecompression reads the request's Content-Encoding, wraps the body in a matching br, deflate or gzip decompression stream and removes the header. It caps the decompressed size at the request body limit, answering 413 when exceeded.
solid answer
~40 sAfter `builder.Services.AddRequestDecompression()` and `app.UseRequestDecompression()`, a request whose single `Content-Encoding` is `br`, `deflate` or `gzip` has its body replaced by a decompressing stream and the `Content-Encoding` header removed, so model binding and `ReadFromJsonAsync` see plain JSON. Providers live in `RequestDecompressionOptions.DecompressionProviders`, keyed by encoding name, and you can add your own `IDecompressionProvider`. An unsupported encoding or several encodings are not an error: the request passes through untouched and still compressed. Against bombs, the middleware limits the **decompressed** bytes to the endpoint's `[RequestSizeLimit]` metadata or the server's `MaxRequestBodySize` (Kestrel's default is 30,000,000 bytes) and throws a `BadHttpRequestException` with 413 when the limit is crossed. Corrupt data surfaces as an exception when the body is read.
code
csharp · 17 linesbuilder.Services.AddRequestDecompression();
builder.Services.AddControllers();
var app = builder.Build();
app.UseRequestDecompression();
app.MapControllers();
[ApiController, Route("api/prices")]
public class PricesController(PriceImporter importer) : ControllerBase
{
[HttpPost, RequestSizeLimit(50_000_000)] // limit applies to the inflated JSON
public async Task<IActionResult> Import(PriceList list, CancellationToken ct)
{
await importer.ImportAsync(list, ct);
return NoContent();
}
}go deeper
Recall that UseRequestDecompression lets endpoints read gzip, deflate or Brotli request bodies as if they were plain.
Explain how Content-Encoding selects a provider, what happens to unknown or multiple encodings, and that the header is removed.
Protect upload endpoints from decompression bombs with explicit size limits and turn silent pass-through into a clear error.
Decide whether compressed uploads are worth accepting at all, given the CPU and abuse surface they add to public endpoints.
## The scenario A hardware wholesaler's ERP system uploads nightly price lists to `POST /api/prices` as gzip-compressed JSON to save bandwidth, sending `Content-Encoding: gzip`. Without help, ASP.NET Core hands the compressed bytes to the JSON reader, and binding fails. The request decompression middleware fixes that in one place. ## Turning it on ```csharp builder.Services.AddRequestDecompression(); var app = builder.Build(); app.UseRequestDecompression(); ``` Place it before anything that reads the body: endpoints, controllers, or middleware that inspects the payload. ## What it does per request 1. It reads the request's `Content-Encoding`. With no header, nothing happens. 2. If there is **more than one** encoding value, it logs and leaves the request alone. 3. It looks the value up in `RequestDecompressionOptions.DecompressionProviders`, a case-insensitive dictionary that by default holds `br`, `deflate` and `gzip`. 4. On a match it **removes `Content-Encoding`**, replaces `Request.Body` with the provider's decompression stream, wrapped in a size-limited stream, and calls the next middleware. 5. Afterwards it restores the original body and disposes the decompression stream. Decompression is lazy: bytes are inflated only as the endpoint reads the body. ## What it does not do | Situation | Result | |---|---| | `Content-Encoding: zstd` (no provider) | request passed on unchanged, still compressed | | `Content-Encoding: gzip, br` | passed on unchanged | | Invalid gzip or deflate data | `InvalidDataException` when the body is read | | Invalid Brotli data | `InvalidOperationException` when the body is read | The pass-through cases are not rejected with 415; the endpoint receives bytes it cannot parse, and the failure appears later as a binding or JSON error. If you want a clear 415, check `Content-Encoding` yourself before the body is read. ## Decompression bombs and size limits A small compressed payload can inflate to gigabytes. The middleware therefore limits the **decompressed** size, not the bytes on the wire: - If the endpoint has `IRequestSizeLimitMetadata`, for example `[RequestSizeLimit(...)]` or `[DisableRequestSizeLimit]` on a controller action, that limit applies. - Otherwise the server's `IHttpMaxRequestBodySizeFeature.MaxRequestBodySize` applies; Kestrel's default `MaxRequestBodySize` is 30,000,000 bytes (about 28.6 MB). - Crossing the limit throws a `BadHttpRequestException` with status **413 Payload Too Large**. Disabling the limit (`null`) on an endpoint that accepts compressed bodies removes the bomb protection, which the docs flag as a denial-of-service risk, especially when the body is buffered. ## Adding a provider `IDecompressionProvider` has one method, `GetDecompressionStream(Stream stream)`. Register it under its encoding name: ```csharp builder.Services.AddRequestDecompression(options => options.DecompressionProviders.Add("x-custom", new CustomDecompressionProvider())); ``` ## Details that surprise people - **`Request.ContentLength` still reports the compressed length.** The middleware removes only `Content-Encoding`; code that pre-sizes buffers from `ContentLength` will under-allocate. - **Logging explains silent pass-through.** At `Debug` level the provider logs "No matching request decompression provider found." or "Request decompression is not supported for multiple Content-Encodings.", which is the quickest way to see why an endpoint received compressed bytes. - **Testing from .NET** means setting the header on the content: compress the JSON into a byte array, wrap it in `ByteArrayContent`, set `Content-Type` and add `gzip` to `content.Headers.ContentEncoding`. - **Corrupt archives are not automatically 400s.** Minimal API JSON binding turns a `BadHttpRequestException` into its status code (so the 413 works) and an `IOException` or `JsonException` into 400, and MVC's System.Text.Json input formatter handles `JsonException`; an `InvalidDataException` from a corrupt gzip body is none of those, so it surfaces as an unhandled exception unless your exception handling maps it. ## Relation to response compression The two middleware are independent. Response compression is driven by the request's `Accept-Encoding` and changes what the server **sends**; request decompression is driven by the request's `Content-Encoding` and changes what the endpoint **reads**. Enabling one does not enable the other, and request decompression has no HTTPS switch. ## What interviewers listen for - `Content-Encoding` on the request, not `Accept-Encoding`, triggers it. - The three built-in encodings and the pass-through behaviour for anything else. - The decompressed-size limit and the 413.
- A client sends Content-Encoding: zstd. What does the endpoint see?The built-in providers are `br`, `deflate` and `gzip` only, so the middleware logs that no provider matched and passes the request on with its `Content-Encoding` header and compressed body intact. The endpoint then fails to bind or parse the bytes. Add an `IDecompressionProvider` under `zstd`, or reject such requests with 415 yourself.
- Why does the size limit apply to the decompressed body instead of the bytes received?A compressed payload of a few kilobytes can expand to gigabytes. Kestrel already counts the bytes on the wire, but only the decompressed size reflects the memory and CPU the endpoint will spend, so the middleware wraps the decompression stream in a size-limited stream using the endpoint's limit or `MaxRequestBodySize`, and throws a 413 `BadHttpRequestException` past it.
- UseRequestDecompression rejects unsupported Content-Encoding values with 415.
- Request decompression is triggered by the Accept-Encoding header.
- AddResponseCompression also decompresses incoming request bodies.
- Body size limits apply only to the compressed bytes received on the wire.
- The middleware keeps the Content-Encoding header so endpoints can see it was compressed.