Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional middleware is always executed

I have added a custom middleware to my ASP.NET Core Web-API 2.1 application, which needs to be executed only for certain requests. The problem is, that it is always executed in the pipeline.

Startup.cs

app.UseWhen(context => context.Request.Path.Value.Contains("AWS"), appBuilder =>
{
    app.UseMiddleware<ValidateHeaderHandler>();
});

The code from above completely ignores the condition and always executes the ValidateHeaderHandler middleware.

like image 985
Rohit Ramname Avatar asked Mar 05 '23 09:03

Rohit Ramname


1 Answers

You need to call the UseMiddleware() method on the appBuilder object, not on app directly:

app.UseWhen(context => context.Request.Path.Value.Contains("AWS"), appBuilder =>
{
    appBuilder.UseMiddleware<ValidateHeaderHandler>();
});
like image 198
prd Avatar answered Mar 28 '23 08:03

prd