UseWhen() is a powerful extension method in ASP.NET Core’s IApplicationBuilder interface. It allows you to conditionally add middleware to your request pipeline based on a predicate (a condition). This means you can create dynamic pipelines where specific middleware components are executed only when certain conditions are met.
Syntax app.UseWhen( context => /* Your condition here */, app => /* Middleware configuration for the branch */ );
context: The HttpContext object representing the current request. Predicate (Condition): A function that takes the HttpContext and returns true if the middleware branch should be executed, false otherwise. Middleware Configuration: An action that configures the middleware components that should be executed if the condition is true. This is where you use app.Use(), app.Run(), or other middleware registration methods.
app.Run(async context => { await context.Response.WriteAsync(“Hello from middleware at main chain”); });
Condition: The predicate context.Request.Query.ContainsKey(“username”) checks if the query string contains a parameter named “username”. Branch Middleware: If the “username” parameter is present, the branch middleware is executed. It writes “Hello from Middleware branch” to the response and then calls next to allow the rest of the pipeline to continue. Main Pipeline: The final app.Run middleware is part of the main pipeline. It writes “Hello from middleware at main chain” to the response.
Output If the request contains the “username” query parameter (e.g., /path?username=John), the output will be: Hello from Middleware branch Hello from middleware at main chain If the request does not contain the “username” parameter (e.g., /path), the output will be: Hello from middleware at main chain
When to Use UseWhen() Conditional Features: Enable or disable certain features based on the request (e.g., logging only for certain users, applying caching rules based on query parameters). Dynamic Pipelines: Create pipelines that adapt to different requests (e.g., different authentication middleware for specific routes). A/B Testing: Route a subset of users through alternative middleware branches for experimentation. Debugging and Diagnostics: Apply diagnostic middleware only in development environments.