skip to content

HTTP Pipeline Composition

How ASP.NET Core builds its request pipeline in Program.cs: Use, Run and Map, middleware classes, and the static-file, compression and timeout middleware. Interviewers hand you a misordered one.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

20

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, what shape must a convention-based middleware class have, and how do you add it to the request pipeline?

level: juniorimportance: must knowfreq 70%

basics

~10 s

A public constructor taking RequestDelegate next and a public Invoke or InvokeAsync method that returns Task and takes HttpContext first. Add it with app.UseMiddleware<T>(), usually wrapped in an IApplicationBuilder extension such as UseBrandResolution().

open as a page

In ASP.NET Core, what is a RequestDelegate, and how do app.Use and app.Run differ when you build the request pipeline?

level: juniorimportance: must knowfreq 78%

basics

~10 s

RequestDelegate is the Task-returning delegate that handles one HttpContext. app.Use adds middleware that receives the next delegate and may call it; app.Run adds terminal middleware with no next, so nothing registered after it runs.

open as a page

In ASP.NET Core, how does app.UseStaticFiles() decide which file to serve for a request, and when does it pass the request on instead?

level: juniorimportance: must knowfreq 70%

basics

~20 s

UseStaticFiles maps the URL path onto the web root (wwwroot by default). For a GET or HEAD whose extension has a known content type, it streams the matching file and ends the request; anything else goes to the next middleware.

open as a page

In ASP.NET Core, why does injecting a scoped DbContext into a convention-based middleware's constructor go wrong, and where should it go instead?

level: middleimportance: must knowfreq 66%

basics

~20 s

Convention middleware is built once from the root provider. In Development scope validation throws when the pipeline is built; elsewhere one DbContext is captured and shared by every request. Take the DbContext as an InvokeAsync parameter, or use IMiddleware.

open as a page

In ASP.NET Core 10, what does app.MapStaticAssets() do that app.UseStaticFiles() does not, and when do you still need UseStaticFiles?

level: middleimportance: must knowfreq 58%

basics

~20 s

MapStaticAssets serves wwwroot files as endpoints from a build-time manifest, with fingerprinted URLs, precompressed copies (Brotli added at publish), content-hash ETags and long-lived caching headers. UseStaticFiles is still needed for files the build never saw.

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

In ASP.NET Core, how does middleware implementing IMiddleware differ from convention-based middleware in activation, DI registration and lifetime?

level: middleimportance: should knowfreq 46%

basics

~20 s

An IMiddleware class is resolved per request by IMiddlewareFactory from the request scope, so it must be registered in DI and may take scoped services in its constructor. Convention middleware is created once at startup and needs no registration.

open as a page

In ASP.NET Core, how do app.Map, app.MapWhen and app.UseWhen branch the middleware pipeline, and which one rejoins the main pipeline?

level: middleimportance: should knowfreq 50%

basics

~20 s

Map branches on a path prefix and MapWhen on a Func<HttpContext, bool>; both hand the request to a separate pipeline that never returns to the main one. UseWhen also branches on a predicate but rejoins the main pipeline unless the branch short-circuits.

open as a page

In ASP.NET Core, what do UseDefaultFiles, UseFileServer and UseDirectoryBrowser each do, and why must UseDefaultFiles run before UseStaticFiles?

level: middleimportance: should knowfreq 35%

basics

~20 s

UseDefaultFiles only rewrites a folder request such as / to its index file; UseStaticFiles, placed after it, serves the file. UseDirectoryBrowser lists folder contents, and UseFileServer combines default files, static files and, if enabled, directory browsing.

open as a page

In an ASP.NET Core 10 app hosting a single-page app, what does app.MapFallbackToFile("index.html") do, and which requests does it not catch?

level: middleimportance: should knowfreq 40%

basics

~10 s

MapFallbackToFile adds a lowest-priority GET/HEAD endpoint with the pattern {*path:nonfile} that serves index.html through the static file middleware. It skips URLs whose last segment contains a dot, other methods, and anything another endpoint matched.

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 custom middleware, why does setting a response header after await next(context) sometimes throw, and how do Response.HasStarted and Response.OnStarting help?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Once the endpoint writes the body, the headers have been sent and Kestrel throws InvalidOperationException on any header or status change. Check Response.HasStarted before changing them, or register Response.OnStarting before next so the header is set just before it goes out.

open as a page

In ASP.NET Core 10, a museum audio-guide API registers authentication, authorization and CORS but calls only app.UseCors(); why do rejected calls reach the browser as CORS errors instead of 401s?

level: seniorimportance: should knowfreq 44%

basics

~20 s

WebApplication adds UseAuthentication and UseAuthorization itself, right after its implicit UseRouting and ahead of everything in Program.cs. Authorization therefore rejects requests before UseCors runs, so the 401 carries no CORS headers. Call UseCors, UseAuthentication and UseAuthorization yourself, in that order.

open as a page

On an ASP.NET Core 10 cycling-club site, how would you serve a members-only downloads folder so that anonymous visitors cannot fetch its files?

level: seniorimportance: should knowfreq 45%

basics

~10 s

Keep the files outside wwwroot, then either serve them with a second UseStaticFiles placed after UseAuthorization under a fallback policy requiring authenticated users, or through an endpoint with RequireAuthorization that returns TypedResults.PhysicalFile.

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

In ASP.NET Core, when app.Map("/guide", ...) handles a request for /guide/tours/7, what do Request.PathBase and Request.Path hold inside the branch?

level: seniorimportance: nice to knowfreq 22%

basics

~20 s

Inside the branch PathBase is the old PathBase plus /guide and Path is /tours/7. Map restores both when the branch returns. Branch code therefore sees paths relative to /guide, while URLs rebuilt from PathBase plus Path still include it.

open as a page