Middleware ordering
Middleware ordering
Middleware is a component that can examine an HTTP request, call the next component, and examine the result on its way back. Registration order determines nesting. A component may instead finish the request without calling the next delegate; this is short-circuiting. The order is part of the application behavior, not merely a style choice.
Use adds a component that can delegate; Run adds a terminal request delegate; Map branches by path prefix. A path branch can adjust Path and PathBase. Routing selects an endpoint, then endpoint-aware middleware can inspect metadata before endpoint execution. WebApplication can insert routing and authentication/authorization middleware automatically in appropriate configurations; explicit placement is needed when ordering matters. In a typical protected pipeline, exception handling surrounds later work, routing precedes endpoint-aware authorization, and authentication precedes authorization. Static files can short-circuit; protect private files separately. CORS is not authentication; forwarded headers must be accepted only from configured trusted proxies. Request-scoped objects and HttpContext must not be captured in singleton state or used after completion.
Baseline: .NET 10 / C# 14. Examples are independent Web SDK projects, with source files shown below or in the companion fixture. All expected outputs are reasoned, not executed. Run only in an isolated environment with an approved SDK, no real data, no launch profile and no external network. The finite loopback host uses ephemeral data protection keys and a test-only cookie container. No production security configuration is implied.
Trace nested middleware
Per-request state records entry and exit. A completion task reports the final sequence even if the client receives the body before the outer component unwinds.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();var trace = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);app.Use(async (ctx, next) =>{ ctx.Items["trace"] = new List<string> { "A in" }; await next(ctx); ((List<string>)ctx.Items["trace"]!).Add("A out"); // Report completion through a separate task, not a late header. trace.TrySetResult(string.Join(", ", (List<string>)ctx.Items["trace"]!));});app.Use(async (ctx, next) =>{ var steps = (List<string>)ctx.Items["trace"]!; steps.Add("B in"); await next(ctx); steps.Add("B out");});app.MapGet("/trace", (HttpContext ctx) =>{ ((List<string>)ctx.Items["trace"]!).Add("endpoint"); return "done";});using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var response = await client.GetAsync("/trace", deadline.Token); response.EnsureSuccessStatusCode(); var observed = await trace.Task.WaitAsync(deadline.Token); Check(observed == "A in, B in, endpoint, B out, A out", "nesting"); Console.WriteLine(observed);}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Expected console observation (unexecuted):
A in, B in, endpoint, B out, A outThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Short-circuit a maintenance route
The middleware returns a 503 without reaching the route handler. An unrelated route continues. This is a toy path guard, not authorization.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.Use(async (ctx, next) =>{ if (ctx.Request.Path == "/closed") { ctx.Response.StatusCode = 503; await ctx.Response.WriteAsync("Maintenance"); return; } await next(ctx);});app.MapGet("/closed", () => "Should not run");app.MapGet("/open", () => "Ready");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var closed = await client.GetAsync("/closed", deadline.Token); using var open = await client.GetAsync("/open", deadline.Token); Check((int)closed.StatusCode == 503 && (await closed.Content.ReadAsStringAsync(deadline.Token)) == "Maintenance", "closed route"); Check(open.IsSuccessStatusCode && (await open.Content.ReadAsStringAsync(deadline.Token)) == "Ready", "open route"); Console.WriteLine("503 / 200");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Expected console observation (unexecuted):
503 / 200The assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Inspect endpoint selection after routing
Explicit UseRouting makes endpoint metadata available to the following component. An OnStarting callback adds a lab header before the response begins.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.UseRouting();app.Use(async (ctx, next) =>{ var label = ctx.GetEndpoint()?.Metadata.GetMetadata<EndpointNameMetadata>()?.EndpointName ?? "none"; ctx.Response.OnStarting(() => { ctx.Response.Headers["X-Lab-Endpoint"] = label; return Task.CompletedTask; }); await next(ctx);});app.MapGet("/status", () => "Ready").WithName("Status");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var response = await client.GetAsync("/status", deadline.Token); Check(response.IsSuccessStatusCode && response.Headers.GetValues("X-Lab-Endpoint").Single() == "Status", "endpoint metadata"); Console.WriteLine("Status");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Expected console observation (unexecuted):
StatusThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Common mistakes and limitations
Do not write a second response after a terminal branch. Do not modify headers after the response starts; use OnStarting for headers that depend on downstream work. Avoid assuming that framework-inserted middleware will appear at the exact position you intended; use explicit order for endpoint-sensitive controls.
Practice and recap
Insert C between A and B in the first example. Predict all entries and exits, then design a short-circuit test at C.
Use the fixture assertions to verify the behavior after modification. Explain the observed result before moving to the next lesson.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Middleware ordering — knowledge check
Apply the lesson concepts to the following scenarios.
A calls next, B calls next, endpoint returns. Which exits first?
What happens if a middleware returns without calling next?
When should endpoint-aware middleware inspect metadata?
When can OnStarting set a response header?
Why avoid keeping HttpContext in a singleton?