HeadlinesBriefing favicon HeadlinesBriefing.com

ASP.NET Core API Branching Guide

DEV Community •
×

Developers building ASP.NET Core apps with separate public and private API surfaces face a common challenge: applying security middleware to only one surface without cluttering code. The recommended solution is pipeline branching using `UseWhen()`, which creates conditional middleware chains based on route prefixes like `/_api` or `/api`. This maintains clean separation of concerns.

Branching after `UseRouting()` ensures optimal performance by skipping middleware execution for non-matching routes. For more granular control, endpoint metadata profiles allow per-controller middleware rules, though they require routing to resolve first. This pattern keeps middlewares pure and configuration centralized, avoiding logic pollution within individual middleware classes.

For teams using Minimal APIs, route groups offer an even cleaner approach, but controllers still favor the `UseWhen()` method. The key is ordering: branch after routing but before authentication and endpoint mapping. This architecture scales well, letting you apply security policies selectively while keeping your startup configuration readable and maintainable.