管道中的 MapGet 执行顺序

MapGet execution sequence in pipeline

我有2段代码

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

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

区别仅在于 app.MapGet()
的位置 对于这两个代码,先执行 app.Use(),然后执行 app.MapGet()
这是什么原因呢?为什么流水线不总是按照中间件的顺序执行?

引用自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.

所以答案是因为 WebApplication.CreateBuilder(args) 默认情况下会对请求管道进行排序,以使端点始终 运行 最后,除非您明确表示要更改该顺序。