In ASP.NET Core 10, how do you turn on response compression for a JSON API, and why might a JSON response still come back uncompressed?
answer
- one service call, one pipeline call
- AddResponseCompression + UseResponseCompression
- client must send Accept-Encoding
- EnableForHttps defaults to false
- ResponseCompressionDefaults.MimeTypes
basics
~20 sCall builder.Services.AddResponseCompression() and app.UseResponseCompression() ahead of whatever writes the response. A JSON response still goes out uncompressed when the client sent no Accept-Encoding, the request is HTTPS (EnableForHttps defaults to false), or its content type isn't listed.
solid answer
~40 sRegister the services with `builder.Services.AddResponseCompression()` and add `app.UseResponseCompression()` ahead of the middleware and endpoints whose output should shrink; it wraps the response body for everything after it. With no providers configured it offers Brotli (`br`) and Gzip. A response is compressed only when all of these hold: the request's `Accept-Encoding` names a supported encoding with a non-zero quality; the request is plain HTTP, or `EnableForHttps` is `true` (the default is `false`); the response's `Content-Type` is in the configured list (`application/json` is in the defaults, `application/problem+json` is not); and the response carries no `Content-Encoding` or `Content-Range` yet. When it compresses, it sets `Content-Encoding`, adds `Vary: Accept-Encoding` and drops `Content-Length`. The usual surprise is HTTPS: a browser calling `https://localhost` gets nothing compressed until you opt in.
code
csharp · 15 linesvar builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression(options =>
{
// The public catalogue holds no secrets, so HTTPS compression is acceptable here
options.EnableForHttps = true;
});
var app = builder.Build();
app.UseResponseCompression();
app.MapGet("/api/catalogue", async (CatalogueService catalogue, CancellationToken ct) =>
TypedResults.Ok(await catalogue.GetAllAsync(ct)));
app.Run();go deeper
Remember the two calls, that the client must send Accept-Encoding, and that HTTPS responses are not compressed unless you opt in.
Walk through the four checks a response must pass, the default MIME list and the headers a compressed response carries.
Diagnose a response that stays uncompressed across clients, proxies and HTTPS, and decide whether the app or the edge should compress.
Weigh bandwidth saved against CPU spent per response and security exposure, and set a policy for which tier owns compression.
## Turning it on Response compression is a middleware in `Microsoft.AspNetCore.ResponseCompression`, part of the shared framework. It needs two calls: ```csharp builder.Services.AddResponseCompression(); var app = builder.Build(); app.UseResponseCompression(); ``` `AddResponseCompression` registers `ResponseCompressionOptions` and the provider that makes the decisions. `UseResponseCompression` swaps the response body for a compressing wrapper, so it affects whatever writes the body **after** it in the pipeline: Minimal API handlers, controllers, Razor output. Middleware registered before it, and anything that writes before reaching it, is not compressed. With no providers added, the middleware offers **Brotli** (`br`) and **Gzip** (`gzip`), in that order. ## The checks every response must pass For a hardware wholesaler's `GET /api/catalogue`, which returns a few megabytes of JSON, compression happens only if: 1. **The request has an `Accept-Encoding` header.** Without one the middleware does nothing at all. The header must name `br`, `gzip` or `*` with a quality above zero; `identity` alone means "do not encode". 2. **The HTTPS gate allows it.** On an HTTPS request the middleware compresses only when `EnableForHttps` is `true` or the response has opted in through `IHttpsCompressionFeature`. `EnableForHttps` defaults to `false` because of the CRIME and BREACH attacks. 3. **The content type is eligible.** The response must have a `Content-Type`, and its media type (parameters such as `charset` are ignored) must be in `MimeTypes`, or in the defaults when `MimeTypes` is empty, and not in `ExcludedMimeTypes`. 4. **Nobody encoded it already.** A response that already has `Content-Encoding` or `Content-Range` is left alone. ## The default content types `ResponseCompressionDefaults.MimeTypes` holds: | Group | Types | |---|---| | General | `text/plain` | | Static files | `text/css`, `application/javascript`, `text/javascript` | | MVC | `text/html`, `application/xml`, `text/xml`, `application/json`, `text/json` | | WebAssembly | `application/wasm` | Types that are **not** in the list include `application/problem+json`, so ProblemDetails error bodies stay uncompressed, and `image/svg+xml`. ## What a compressed response looks like When the middleware compresses, it adds `Content-Encoding`, adds `Accept-Encoding` to `Vary` so shared caches keep the variants apart, and removes `Content-Length` because the final size is not known in advance: ```http GET /api/catalogue HTTP/1.1 Accept-Encoding: gzip, br HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Content-Encoding: br Vary: Accept-Encoding Transfer-Encoding: chunked ``` ## Why it still is not compressed A short diagnostic list for "I enabled it and nothing changed": - **The client never asked.** An `HttpClient` whose handler has no `AutomaticDecompression` set sends no `Accept-Encoding`, so a .NET caller gets plain JSON. - **The request is HTTPS** and `EnableForHttps` is still `false`. - **The content type is not listed**, for example `application/problem+json` or a custom vendor type. - **The middleware sits after the writer**, for example after a static file middleware that already answered. - **A proxy removed the header.** The ASP.NET Core docs note that Nginx drops `Accept-Encoding` when it proxies, so the app never sees it. - **Something upstream encoded it** and set `Content-Encoding` first. Also worth knowing: Kestrel and HTTP.sys have no compression of their own, and the providers default to `CompressionLevel.Fastest`, trading ratio for CPU on every response. ## Let the logs tell you The provider logs each decision at `Debug` level under the `Microsoft.AspNetCore.ResponseCompression` category. Raising that category in `appsettings.Development.json` turns guesswork into a one-line answer: ```json { "Logging": { "LogLevel": { "Microsoft.AspNetCore.ResponseCompression": "Debug" } } } ``` Typical messages are "No response compression available for HTTPS requests. See ResponseCompressionOptions.EnableForHttps.", "Response compression is not enabled for the Content-Type ...", and "The response will be compressed with 'br'." ## When not to bother Compression is not free. The documentation advises against compressing responses smaller than roughly 150 to 1,000 bytes, where the overhead can make the output larger, and against recompressing formats that are already compressed, such as PNG images. The middleware itself has no minimum-size option, so it compresses every eligible response whatever its length. For a catalogue endpoint returning megabytes of JSON the saving is large; for a 200-byte health check it is noise. ## What interviewers listen for - Both registration calls and that placement decides what gets wrapped. - `Accept-Encoding` as the client's opt-in. - The HTTPS default and its security reason. - The MIME type list, and that ProblemDetails bodies are outside it.
- How do you prove from the outside that the catalogue response is actually compressed?Send the request with `Accept-Encoding: gzip, br` and inspect the response headers: a compressed response carries `Content-Encoding: br` or `gzip`, `Vary: Accept-Encoding`, and no `Content-Length`. Repeat without the header and the body should come back larger and without `Content-Encoding`. Check the `Server` header too, since IIS can add its own gzip.
- Why are ProblemDetails error responses not compressed even when the success responses are?ProblemDetails bodies use `application/problem+json`, which is not in `ResponseCompressionDefaults.MimeTypes`. To include it, set `MimeTypes` to `ResponseCompressionDefaults.MimeTypes.Concat(["application/problem+json"])`; assigning a list without the defaults replaces them, so JSON and HTML would stop being compressed.
- Kestrel compresses responses by itself once the middleware package is referenced.
- Response compression is applied to HTTPS responses by default.
- application/json has to be added to MimeTypes before JSON gets compressed.
- The middleware compresses every response, whether or not the client sent Accept-Encoding.
- Brotli has to be registered explicitly; out of the box only gzip is offered.