var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton(); var app = builder.Build(); if (!app.Environment.IsDevelopment()) throw new InvalidOperationException("This trace observer is development-only"); app.Use(async (context, next) => { if (context.Request.Path != "/order") { await next(context); return; } var trace = new List { "outer-in" }; context.Items["trace"] = trace; await next(context); trace.Add("outer-out"); context.RequestServices.GetRequiredService().Last = string.Join(">", trace); }); app.Use(async (context, next) => { if (context.Request.Path != "/order") { await next(context); return; } var trace = (List)context.Items["trace"]!; trace.Add("inner-in"); await next(context); trace.Add("inner-out"); }); app.MapGet("/order", (HttpContext context) => { ((List)context.Items["trace"]!).Add("endpoint"); return TypedResults.Text("handled"); }); app.MapGet("/trace", (TraceState state) => TypedResults.Text(state.Last)); app.Run(); public sealed class TraceState { public string Last { get; set; } = "none"; }