somedotnetguy
somedotnetguy

Reputation: 938

Whats the point in calling app.Run() multiple times in ASP.NET Core?

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 ???

Upvotes: 3

Views: 1359

Answers (2)

Kirk Larkin
Kirk Larkin

Reputation: 93273

In ASP.NET Core 6, Microsoft introduced WebApplication, an attempt to simplify and unify setup and such for running a web app. WebApplication implements both IHost and IApplicationBuilder, both of which have existed from the earliest days in ASP.NET Core. As you've seen, both of these interfaces include a Run extension method of some form:

  • IApplicationBuilder.Run:

    Adds a terminal middleware delegate to the application's request pipeline.

  • IHost.Run:

    Runs an application and blocks the calling thread until host shutdown is triggered and all IHostedService instances are stopped.

The preceding descriptions (taken from the linked docs) show that the functions do very different things. Before the unification of WebApplication, these two methods were more obviously separate, as one was called in Program.cs on an IHost and the other was called in Startup.Configure on an IApplicationBuilder.

Upvotes: 4

somedotnetguy
somedotnetguy

Reputation: 938

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.

  1. Adding terminal middleware

  2. Actually running the server

App.Run()

Runs an application and block the calling thread until host shutdown.

The similarity of the name is VERY CONFUSING!

Upvotes: 2

Related Questions