Yesterday I blogged about the usage of the MapWhen() method to branch the request pipeline in ASP.NET Core. What I didn’t mention is that in a first attempt I used the Map() method instead of the MapWhen() method.
Map() will branch the request based on the specified request path whereas MapWhen() allows you to specify a predicate giving you more options on what criteria should be used for branching.
Let’s have a second look at the MapWhen() implementation I was using:
You would think I could replace this with the following Map() alternative:
This turns out not to be the case. Apart from the predicate logic, another difference between Map() and MapWhen() is that Map() will add MapMiddleware to the pipeline while MapWhen
will add MapWhenMiddleware to the pipeline. An important difference between these 2 middleware is that Map() will update the Request.Path and Request.PathBase to account for branching based on path (trimming the matched path segment off Request.Path and appending it to Request.PathBase).
In the example above, the ServerSideEvents middleware I’ve added to the pipeline will listen to requests on ‘api/bel/api/bel’ what is not what I want. To achieve the expected behavior, I should rewrite the middleware like this: