App.Use
can/should call the next middle ware. OK.
App.Run
is terminal, no other middleware is executed after that. OK
WHY then have multiple calls to App.Run
in succession ?? Sure, one uses the parameterized overload, but why does App.Run(...)
need to be followd by App.Run
?? Does it make any sense ?? Or is it simply convention to always have App.Run()
at the end even if its never reached ???
From MS Learn:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
// Do work that can write to the Response.
await next.Invoke();
// Do logging or other work that doesn't write to the Response.
});
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from 2nd delegate.");
}); <-- WE ALREADY HAVE THIS... ???
app.Run(); // <-- WHY THIS ???
CodePudding user response:
The app.Run() at the end of the code is not necessary. It is most likely there as a convention, to signal the end of the configuration for the web application.
The app.Run() method without any arguments simply starts the application and begins processing requests. However, in this code, the application has already been started and is processing requests through the use of the app.Use() and app.Run() methods with arguments.
These methods are used to specify middleware and request handlers for the application, and they are invoked when a request is received by the application.
The app.Run() method at the end of the code will never be reached, because it is after the request handling has already been configured and the application has been started.
CodePudding user response:
OK, after testing I know now, that the application simply wont run (or at least immediately stops) if not calling app.Run()
at the end. Despite its similar names, those two methods seem to do very different things.
Adding terminal middleware
Actually running the server
Runs an application and block the calling thread until host shutdown.
The similarity of the name is VERY CONFUSING!