⚙️ Fix a Feature Flag Middleware Running in the Wrong Order
Custom middleware that checks a feature flag and short-circuits the pipeline (returning a 404 or a maintenance page when a flag is off) only works correctly if it runs before the middleware whose behavior it’s meant to gate — registering it after routing or after authentication means the gated logic, or the authentication challenge itself, has already executed by the time the flag check happens, so disabling a feature flag doesn’t actually prevent the thing it was supposed to turn off.
🔎 The Problem
var app = builder.Build(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseMiddleware<FeatureFlagGateMiddleware>(); // registered too late app.MapControllers(); // FeatureFlagGateMiddleware checks a flag and wants to block access, // but auth + routing already ran before it gets a chance to intervene
✅ Fix: Register the Gate Before Whatever It’s Supposed to Block
- Move
app.UseMiddleware<FeatureFlagGateMiddleware>()to beforeUseRouting()(or immediately after, but before auth) if the gate is meant to block access to a feature regardless of authentication state. - If the gate specifically needs to know the authenticated user to decide (per-user flag rollout), place it after
UseAuthentication()but still beforeUseAuthorization()and any endpoint-specific middleware it’s meant to control. - Add an integration test that flips the flag off and asserts the gated behavior actually doesn’t happen, rather than only testing the flag’s own logic in isolation — pipeline ordering bugs don’t show up in a unit test of the middleware alone.
Middleware order isn’t a style choice — a gate placed after the door it’s meant to guard has already let everyone through.




