Skip to content

5.10 — Tour of the Built-in Middleware

← Roadmap · Section: 5. Middleware and the Request Pipeline Prev: 5.9 Request body buffering · Next: 5.11 Exception middleware

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

ASP.NET Core ships with roughly twenty middleware components. None of them are on by default — you add the ones you need.

  • The ones almost every app uses: exception handling, HTTPS redirection, static files, routing, CORS, authentication, authorization, endpoints.
  • Several need a matching builder.Services.Add... call, and forgetting it throws at startup.
  • Knowing what exists saves you writing middleware that already ships in the box.

Definitions

Term What it is What it means
Built-in middleware framework components Middleware shipped with ASP.NET Core, added via Use... methods.
Use... method an extension method Adds middleware to the pipeline. Phase 2 of Program.cs.
Add... method an extension method Registers the services that middleware needs. Phase 1.
UseExceptionHandler middleware Catches unhandled exceptions from below and produces a clean response.
UseHsts middleware Sends Strict-Transport-Security, telling browsers to always use HTTPS.
UseHttpsRedirection middleware Redirects HTTP requests to the HTTPS equivalent.
UseStaticFiles middleware Serves files from wwwroot. Short-circuits on a match.
UseRouting middleware Matches the request to an endpoint. Does not execute it.
UseCors middleware Applies a cross-origin policy and answers preflight requests.
UseAuthentication middleware Establishes who the caller is; populates context.User.
UseAuthorization middleware Decides whether the caller may proceed.
UseResponseCompression middleware Compresses responses with gzip or Brotli.
UseRateLimiter middleware (.NET 7+) Rejects requests over a configured limit with 429.
UseOutputCache middleware (.NET 7+) Caches whole responses server-side.

The concept

Nothing is on by default

This follows from ASP.NET Core's opt-in design (4.1). A new minimal API project has a nearly empty pipeline. You add what you need.

The benefit is that you pay only for what you use, and the whole application's behaviour is visible in Program.cs. The cost is that forgetting something produces silent misbehaviour rather than an error — no UseAuthentication means User is never populated and every [Authorize] endpoint returns 401 with no explanation.

The two-call pattern

Many middleware need services registered before the pipeline is built:

builder.Services.AddCors();              // phase 1 — register services
var app = builder.Build();
app.UseCors();                           // phase 2 — add to the pipeline

Forget the Add and you get a startup exception like "Unable to find the required services. Please add all the required services by calling IServiceCollection.AddCors" — which is at least a clear message pointing at the fix.

Which need both:

Middleware Needs an Add call?
UseCors ✅ AddCors()
UseAuthentication ✅ AddAuthentication()
UseAuthorization ✅ AddAuthorization()
UseResponseCaching ✅ AddResponseCaching()
UseResponseCompression ✅ AddResponseCompression()
UseRateLimiter ✅ AddRateLimiter(...)
UseOutputCache ✅ AddOutputCache()
UseSession ✅ AddSession() + a distributed cache
UseHealthChecks / MapHealthChecks ✅ AddHealthChecks()
UseStaticFiles ❌
UseHttpsRedirection ❌
UseExceptionHandler ❌ (but AddProblemDetails() improves it)
UseRouting ❌

How it works

The simple version — the ones you will actually use

Error handling

app.UseDeveloperExceptionPage();      // dev only — full stack trace in the browser
app.UseExceptionHandler("/error");    // production — clean response, nothing leaked
app.UseStatusCodePages();             // adds a body to bare 404s and 401s

UseStatusCodePages is underused. Without it a 404 from routing has an empty body, which confuses API clients expecting JSON. UseStatusCodePages() gives them something. See 5.11.

HTTPS and security headers

app.UseHttpsRedirection();            // 307 redirect HTTP → HTTPS
app.UseHsts();                        // Strict-Transport-Security header

⚠️ UseHsts should be production-only. It tells browsers to refuse HTTP for this host for months, and browsers cache that aggressively. Enable it locally and you can lock yourself out of http://localhost across every project on that port. See 17.5.

⚠️ UseHttpsRedirection behind a TLS-terminating proxy causes an infinite loop — the app sees http, redirects, the proxy forwards http again (4.2).

Static files

app.UseStaticFiles();                 // serve wwwroot
app.UseDefaultFiles();                // serve index.html for a directory — BEFORE UseStaticFiles
app.MapStaticAssets();                // .NET 9+ — fingerprinting and precompression

See 4.10.

Routing, CORS, auth

app.UseRouting();
app.UseCors("Default");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

The order here is the canonical one and matters enormously — 5.2.

How it actually works — the performance ones

Response compression

builder.Services.AddResponseCompression(options =>
{
    options.EnableForHttps = true;                 // off by default — see below
    options.Providers.Add<BrotliCompressionProvider>();
    options.Providers.Add<GzipCompressionProvider>();
});

app.UseResponseCompression();

⚠️ EnableForHttps is false by default because of the BREACH and CRIME attacks, where an attacker who can inject content and observe compressed sizes can extract secrets. Turning it on is usually fine for JSON APIs with no reflected secrets, and genuinely risky for pages echoing tokens back.

⚠️ Do not compress in the app if your reverse proxy already does. Nginx and most CDNs compress better and it costs your app nothing. Doing both wastes CPU.

Rate limiting (.NET 7+)

builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("api", limiter =>
    {
        limiter.PermitLimit = 100;
        limiter.Window = TimeSpan.FromMinutes(1);
        limiter.QueueLimit = 0;
    });

    options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});

app.UseRateLimiter();

⚠️ Register it after UseForwardedHeaders, or every request appears to come from the proxy and shares one bucket. See 17.10.

Output caching (.NET 7+)

builder.Services.AddOutputCache(options =>
{
    options.AddBasePolicy(p => p.Expire(TimeSpan.FromSeconds(30)));
});

app.UseOutputCache();

app.MapGet("/products", GetProducts).CacheOutput();

Different from response caching: output caching stores the response on the server and can be invalidated by tag, whereas response caching only sets HTTP headers and relies on the client or a proxy to honour them. See 19.6.

The deeper detail — ones worth knowing exist

app.UseForwardedHeaders();       // real client IP behind a proxy — see 4.2
app.UseRequestLocalization();    // culture from Accept-Language — see 21.8
app.UseSession();                // server-side session. Makes your app stateful.
app.UseWebSockets();             // raw WebSocket support
app.UseRequestTimeouts();        // .NET 8+ — per-endpoint timeouts
app.UseRequestDecompression();   // .NET 7+ — accept compressed request bodies
app.UseAntiforgery();            // CSRF tokens — see 17.4
app.UseW3CLogging();             // W3C-format access logs
app.UseHttpLogging();            // structured request/response logging — see 5.14

⚠️ UseSession deserves a warning. It makes your application stateful, which breaks horizontal scaling unless you back it with a distributed cache (24.12). For APIs it is almost always the wrong choice — a token carries the state instead.

⚠️ UseRequestTimeouts is a genuinely useful addition most people have not noticed. It cancels the request's CancellationToken after a deadline, so a slow dependency cannot tie up a request indefinitely.


Code

A complete production pipeline using the common set:

var builder = WebApplication.CreateBuilder(args);

// ── phase 1: services the middleware needs ──
builder.Services.AddProblemDetails();
builder.Services.AddCors(o => o.AddDefaultPolicy(p => p
    .WithOrigins("https://app.example.com")
    .AllowAnyHeader()
    .AllowAnyMethod()));
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();
builder.Services.AddResponseCompression(o => o.EnableForHttps = true);
builder.Services.AddRateLimiter(o => o.AddFixedWindowLimiter("api", l =>
{
    l.PermitLimit = 100;
    l.Window = TimeSpan.FromMinutes(1);
}));
builder.Services.AddHealthChecks();
builder.Services.AddControllers();

var app = builder.Build();

// ── phase 2: the pipeline, in canonical order ──
app.UseExceptionHandler();          // outermost — wraps everything below

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

if (!app.Environment.IsDevelopment())
    app.UseHsts();                  // production only

app.UseResponseCompression();
app.UseStaticFiles();               // early — assets skip everything below

app.UseRouting();

app.UseCors();                      // before auth, so preflight is answered
app.UseRateLimiter();               // after forwarded headers, so it sees real IPs

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers().RequireRateLimiting("api");
app.MapHealthChecks("/healthz").ShortCircuit();

app.Run();

Every ordering decision in that pipeline has a reason, and they are all covered in 5.2.


Interview questions

Q: Which middleware does a typical ASP.NET Core API use?

Exception handling first so it wraps everything, then forwarded headers if behind a proxy, HSTS and HTTPS redirection, static files if the app serves any, routing, CORS, rate limiting, authentication, authorization, and finally endpoint mapping. None of them are enabled by default — ASP.NET Core is opt-in, so a new project starts with an almost empty pipeline and you add what you need. That makes the whole application's behaviour readable in Program.cs, at the cost of silent misbehaviour when you forget something.

Q: Why do some middleware need a matching Add call?

Because they depend on services that must be registered before the container is built. UseCors needs the policy configuration from AddCors, UseAuthentication needs the registered schemes and handlers. Since builder.Build() freezes the service collection, those registrations have to happen in the first phase of Program.cs. Forgetting produces a startup exception that names the missing Add method, so it is at least a clear failure.

Q: What is the difference between response caching and output caching?

Response caching only sets HTTP cache headers and relies on the client or an intermediate proxy to honour them — you are asking someone else to cache. Output caching, added in .NET 7, stores the response on the server, so you control it: it works regardless of client behaviour, applies to authenticated requests, and supports invalidation by tag. For server-side caching that you actually control, output caching is the one you want.

Q: Why is EnableForHttps off by default for response compression?

Because of the BREACH and CRIME attack class, where an attacker who can inject content into a response and observe its compressed size can infer secrets in that same response. Compressing over HTTPS is generally fine for JSON APIs that do not reflect secrets back, and genuinely risky for pages that echo tokens. Worth adding that if a reverse proxy or CDN is already compressing, doing it in the application as well is just wasted CPU.


Traps ⚠️

  • Forgetting the matching Add call throws at startup — but only for middleware that needs one.
  • UseHsts in development can lock you out of http://localhost for months, across projects.
  • UseHttpsRedirection behind a TLS proxy causes an infinite redirect loop.
  • UseRateLimiter before UseForwardedHeaders rate-limits the proxy, so all clients share one bucket.
  • UseSession makes the app stateful, breaking horizontal scaling without a distributed cache.
  • Compressing in both the app and the proxy wastes CPU for no benefit.
  • A bare 404 has an empty body unless you add UseStatusCodePages.
  • Nothing is on by default. Missing UseAuthentication means every [Authorize] returns 401 silently.


Sources