'MapGet execution sequence in pipeline
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?
Solution 1:[1]
Quoting from Routing in ASP.NET Core, Routing basics:
Apps typically don't need to call
UseRoutingorUseEndpoints. WebApplicationBuilder configures a middleware pipeline that wraps middleware added inProgram.cswithUseRoutingandUseEndpoints. However, apps can change the order in whichUseRoutingandUseEndpointsrun by calling these methods explicitly. For example, the following code makes an explicit call toUseRouting: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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gunr2171 |
