Rohit Ramname
Rohit Ramname

Reputation: 834

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.

Upvotes: 5

Views: 1896

Answers (1)

prd
prd

Reputation: 2321

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>();
});

Upvotes: 13

Related Questions