I had a use case where I needed to create a branch in the ASP.NET Core request pipeline.
For most requests the default pipeline should be run, but for all requests going to a specific URI different middleware should be executed.
This was the original request pipeline:
And here was my first attempt to create a branch in the request pipeline:
I used the UseWhen method but this didn’t work as expected. Although the middleware specified in the branch was indeed invoked, it also called all the other middleware defined later in the pipeline. This turns out to be expected as when using UseWhen the branch is rejoined to the main pipeline if it doesn't short-circuit or contain a terminal middleware.
I switched to the MapWhen method and this did the trick:
More information: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0#branch-the-middleware-pipeline