skip to content

Compression & Timeout Middleware

Response compression, request decompression and request timeout middleware, plus ShortCircuit endpoints. Interviewers ask why compression is off for HTTPS and when a proxy should compress.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

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?

level: juniorimportance: must knowfreq 55%

answer

  1. one service call, one pipeline call
  2. AddResponseCompression + UseResponseCompression
  3. client must send Accept-Encoding
  4. EnableForHttps defaults to false
  5. ResponseCompressionDefaults.MimeTypes

basics

~20 s

Call 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 s

Register 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 lines
csharp
var 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

for a junior

Remember the two calls, that the client must send Accept-Encoding, and that HTTPS responses are not compressed unless you opt in.

for a middle

Walk through the four checks a response must pass, the default MIME list and the headers a compressed response carries.

for a senior

Diagnose a response that stays uncompressed across clients, proxies and HTTPS, and decide whether the app or the edge should compress.

for a principal

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.
open as a page

In ASP.NET Core 10's response compression, how are the Brotli and Gzip providers chosen and tuned, and how do you change the compressed content types?

level: middleimportance: should knowfreq 35%

basics

~20 s

With no providers configured, Brotli then Gzip are offered; the encoding with the highest Accept-Encoding quality wins, ties going to the earlier provider. Levels come from BrotliCompressionProviderOptions and GzipCompressionProviderOptions (Fastest by default), and MimeTypes replaces the default type list.

open as a page

Why does ASP.NET Core's response compression middleware leave HTTPS responses uncompressed by default, and when would you enable EnableForHttps or compress at a proxy instead?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Compressing HTTPS responses that mix a secret with attacker-influenced input lets an attacker infer the secret from response sizes (CRIME, BREACH). Enable EnableForHttps only for responses without that mix, opt individual responses in or out, or let a proxy compress.

open as a page

In an ASP.NET Core 10 API, a stock report endpoint has a 30-second request timeout but still runs for minutes. What does the timeout middleware actually do, and why might it not stop the work?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The request timeouts middleware only cancels HttpContext.RequestAborted when the limit passes; if that cancellation surfaces as an exception before the response starts, it answers 504. Code that ignores the token keeps running, and nothing fires with a debugger attached.

open as a page

In ASP.NET Core 10, what do app.MapShortCircuit(404, "robots.txt", "wp-admin") and an endpoint's .ShortCircuit() do, and which middleware do they skip?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

ShortCircuit() makes the routing middleware run a matched endpoint immediately and end the request, skipping all middleware after UseRouting. MapShortCircuit maps prefixes to an empty short-circuit endpoint returning a fixed status code, cheaply dropping bot probes.

open as a page

In ASP.NET Core, what does UseRequestDecompression do with a gzip-encoded request body, and how does it protect the app from decompression bombs?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

UseRequestDecompression 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.

open as a page