if i used below dose this considered a middlewear or a endpoint ,and dose middlewears only created using Use() and Run()
app.Map("/" ,async context => await context.Response.WriteAsync("Hello World") )
and alos i want to ask why dose the Use in this code invoked before the Map()
app.UseRouting();
app.Use(async (context, next) =>
{
await context.Response.WriteAsync(MyCustomKeyValue + '\n');
await next();
await context.Response.WriteAsync("The Value Appers there" + '\n');
});
app.Map("/", async (context) =>
{
await context.Response.WriteAsync("From Route /" + '\n');
});
Aman GuptaPosted Sep 14, 2024, 10:10 AM
Hi Mina,
In your first question:
This is considered an endpoint. Map defines a specific route and associates it with a request delegate, which directly handles requests that match the route pattern. This behavior makes Map part of endpoint routing, rather than middleware.
In your second question:
Why is
Useinvoked beforeMap?Middleware (
app.Use) is part of the request processing pipeline, and it executes in the order it's added. Middleware is typically added usingUse(),Map(), orRun(). Middlewares can intercept the request and either handle it or pass it along to the next middleware usingnext(). Theapp.UseRouting()middleware sets up routing but doesn't yet execute the matched endpoint.Endpoint (
app.Map) defines a specific route and request handler but isn't middleware. It's executed after all middleware has run and when theUseEndpoints()middleware is invoked (though not visible here, it's usually added later). Hence, the middleware defined withUse()runs first.Middleware and
Use/Run:Middlewares are typically created using
Use(), which chains to the next middleware, orRun(), which short-circuits the pipeline (i.e., nonext()).app.Use()allows the middleware to pass control to the next one in line (await next()).app.Run()terminates the pipeline, so no further middleware is invoked.So, the order in which middleware and routes are added is critical to how the request is processed. The
Mapendpoint here is invoked after theUse()middleware finishes.