Call app.Run() after configuring a WebApplication. Until that call, the application is not handling HTTP requests; Run starts the server listening so it can respond to them. The call blocks while the application handles requests. section 3.6
Listing 3.3 The default Program.cs file that configures and runs a WebApplication
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); #1
WebApplication app = builder.Build(); #2
app.MapGet("/", () => "Hello World!"); #3
app.Run(); #4
This minimal API builds the application, maps GET requests for / to a “Hello World!” response, then starts the server with app.Run(). section 3.6
The same startup order applies to larger applications: register services, build the WebApplication, add middleware, map endpoints, and call app.Run(). A Razor Pages application follows that pattern even though it configures more middleware. section 13.1.2
Do not confuse app.Run() with app.Run(lambda). The latter adds terminal middleware: its lambda receives an HttpContext and generates a response whenever a request reaches it. Middleware placed after it will not execute, so put it last in its pipeline or branch. section 31.1.1 section 31.4
Listing 31.1 Creating simple middleware using the Run extension
app.Run(async (HttpContext context) => #1 { context.Response.ContentType = "text/plain"; #2 await context.Response.WriteAsync( #3 DateTimeOffset.UtcNow.ToString()); #3 }); app.UseStaticFiles(); #4 #1 Uses the Run extension to create simple middleware that always returns a response #2 You should set the content-type of the response you’re generating; text/plain is the default value. #3 Returns the time as a string in the response. The 200 OK status code is used if not explicitly set. #4 Any middleware added after the Run extension will never execute.
The lambda writes the current time to the response. The static-file middleware shown after it cannot run for requests that reach this Run component. section 31.1.1
