2

I have 2 pieces of code

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Use(async (context, next) =>
{
    if (context.Request.Headers["token"] != "my_token")
    {
        context.Response.StatusCode = 401;
        return;
    }

    await next();
});

app.Run();

and

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
    
app.Use(async (context, next) =>
{
    if (context.Request.Headers["token"] != "my_token")
    {
        context.Response.StatusCode = 401;
        return;
    }

    await next();
});

app.MapGet("/", () => "Hello World!");

app.Run();

Difference is only location of app.MapGet()
For the both code app.Use() is executed firstly, then app.MapGet().
What is a reason of this? Why isn't pipeline always executed based on the sequence of the middlewares?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
giorgi02
  • 683
  • 6
  • 13

1 Answers1

3

Quoting from Routing in ASP.NET Core, Routing basics:

Apps typically don't need to call UseRouting or UseEndpoints. WebApplicationBuilder configures a middleware pipeline that wraps middleware added in Program.cs with UseRouting and UseEndpoints. However, apps can change the order in which UseRouting and UseEndpoints run by calling these methods explicitly. For example, the following code makes an explicit call to UseRouting:

app.Use(async (context, next) =>
{
    // ...
    await next(context);
});

app.UseRouting();

app.MapGet("/", () => "Hello World!");

[...]

If the preceding example didn't include a call to UseRouting, the custom middleware would run after the route matching middleware.

So the answer is because WebApplication.CreateBuilder(args) by default will order the request pipeline such that endpoints always run last, unless you explicitly say you want to change that order.

gunr2171
  • 16,104
  • 25
  • 61
  • 88