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:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
app.UseHttpsRedirection(); | |
app.UseStaticFiles(); | |
app.UseRouting(); | |
app.UseCors(); | |
app.UseAuthentication(); | |
app.UseAuthorization(); | |
app.UseSecurityHeaders(); | |
app.UseCookiePolicy(); | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
app.UseOpenApi(p => p.Path = "/api/openapi.json"); | |
app.UseSwaggerUi3(settings => | |
{ | |
settings.Path = "/api"; | |
settings.DocumentPath = "/api/openapi.json"; | |
}); | |
} | |
else | |
{ | |
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. | |
app.UseHsts(); | |
} | |
app.UseSerilogRequestLogging(); | |
app.UseMiddleware<ErrorHandlerMiddleware>(); | |
app.UseEndpoints(endpoints => | |
{ | |
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); | |
endpoints.MapFallbackToController("Index", "Home"); | |
}); | |
} |
And here was my first attempt to create a branch in the request pipeline:
app.UseWhen(r=> r.Request.Path.StartsWithSegments("/api/bel"), config => { | |
//Add middleware for this branch here | |
config.MapServerSentEvents("/api/bel"); | |
}); |
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:
app.MapWhen(r=> r.Request.Path.StartsWithSegments("/api/bel"), config => { | |
//Add middleware for this branch here | |
config.MapServerSentEvents("/api/bel"); | |
}); |
More information: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0#branch-the-middleware-pipeline