Can I apply middleware to the app in any order?

In C# ASP.NET does the order of middleware application matter?

The following 2 code snippets:

public class Startup
{
    ...
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        setUpMVCRoutes(app);
        app.UseSwaggerUi("foobar/api", "/foobar/v3/api.json");
        app.UseSwaggerGen("foobar/{apiVersion}/api.json");
        app.UseDefaultFiles();
        app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
        app.UseStaticFiles();
        app.UseIdentity();
        app.UseCookieAuthentication();
    }
    ...
}

and this

public class Startup
{
    ...
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseIdentity();
        app.UseCookieAuthentication();
        app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
        app.UseDefaultFiles();
        app.UseStaticFiles();
        setUpMVCRoutes(app);
        app.UseSwaggerGen("foobar/{apiVersion}/api.json");
        app.UseSwaggerUi("foobar/api", "/foobar/v3/api.json");
    }
    ...
}

Is there any difference? I imagine that if this middleware works similar to python decorators or just pipe of functions which do something and pass the results to the next function, then it might matter.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It has nothing to do with ASP.NET but with OWIN hosting implementation.

Order matters. For example, if you register a middleware that should listen errors after any other middleware, there’s a chance of not being able to log some errors.

This is just an hypothetical case, but it can give you a good hint of how other scenarios may work if you change the order of middleware registrations.

or just pipe of functions which do something and pass the results to
the next function, then it might matter.

That’s it! This is the reason of why order matters.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x