5

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.

CrabMan
  • 1,578
  • 18
  • 37

1 Answers1

4

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.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • 1
    Well, how do I know what should come after what? I wanted to group middleware which should only work in development environment, middleware which should only work in production environment, and common middleware in different methods. – CrabMan Apr 22 '16 at 12:37
  • @crabman specific middleware docs will tell you if order matters or not and if our matters, in which order you should configure it.. – Matías Fidemraizer Apr 22 '16 at 14:03