Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Single app.UseWhen vs multiple app.UseWhen

In ASP .NET Core app want to make one of my controllers sessionless. So I do the following:

app.UseWhen(
context => context.GetRouteValue("controller") is not "SomeValue",
app => app.UseMiddleware<SessionMiddleware>());

Then I decided to disable some other middleware for this controller. And I wonder if there is a difference between this

app.UseWhen(
context => context.GetRouteValue("controller") is not "SomeValue",
app =>
{
    app.UseMiddleware<SessionMiddleware>();
    app.UseMiddleware<SomeOtherMiddleware>();
});

and this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.UseWhen(
context => context.GetRouteValue("controller") is not "SomeValue",
app => app.UseMiddleware<SessionMiddleware>());

app.UseWhen(
context => context.GetRouteValue("controller") is not "SomeValue",
app => app.UseMiddleware<SomeOtherMiddleware>());

It should behave the same, but is there any overhead in registering two middlewares separately? Or both calls will end up being the same (optimized by compiler)?

>Solution :

The source code for UseWhen is here: https://github.com/dotnet/aspnetcore/blob/3f8edf130a14d34024a42ebd678fa3f699ef5916/src/Http/Http.Abstractions/src/Extensions/UseWhenExtensions.cs#L22.

There would be some small overhead for calling it twice but since this is only done once on startup and not per request, I’d say it doesn’t matter.

I would personally prefer having just one as you don’t need to duplicate conditions.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading