WebApplication is the configured ASP.NET Core application that runs a web server and handles requests. In Program.cs, create a WebApplicationBuilder, register any needed services, then call Build() to obtain the WebApplication. Configure it before calling Run(), which starts listening for requests. section 3.6 section 3.8
Once the application has been built, use it to:
- Add middleware with Use* methods. Middleware processes requests in sequence, so order matters: a component can use objects created earlier in the pipeline, not later ones. section 3.7.2
- Map endpoints that generate responses for matching requests, such as MapGet("/", () => "Hello World!"). section 3.6 section 3.7.2
- Call Run() after configuring the pipeline and endpoints to start handling requests. section 3.7
Service registration belongs on WebApplicationBuilder before Build(); middleware and endpoint registration belong on WebApplication afterward. WebApplication adds routing and endpoint middleware automatically. Its Environment property also lets you vary behavior by runtime environment—for example, enabling HTTP request logging only in development. section 3.7.2 section 3.8
Listing 3.4 The Program.cs file for a more complex example minimal API
using Microsoft.AspNetCore.HttpLogging;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpLogging(opts => #1
opts.LoggingFields = HttpLoggingFields.RequestProperties); #1
builder.Logging.AddFilter( #2
"Microsoft.AspNetCore.HttpLogging", LogLevel.Information); #2
WebApplication app = builder.Build();
if (app.Environment.IsDevelopment()) #3
{
app.UseHttpLogging(); #4
}
app.MapGet("/", () => "Hello World!");
app.MapGet("/person", () => new Person("Andrew", "Lock")); #5
app.Run();
public record Person(string FirstName, string LastName); #6
This working minimal API registers HTTP logging on the builder, conditionally adds its middleware to the application, maps two endpoints, and then runs the server. A request to /person returns a JSON representation of a Person record. section 3.7
One middleware for every request
For a simple holding page, build the application, call app.UseWelcomePage(), then call app.Run(). The welcome-page middleware returns the same HTML response for every request path. UseWelcomePage is an extension method rather than a method defined directly on WebApplication. section 4.2.1
The same setup pattern works beyond minimal APIs. A Razor Pages application registers its services before Build(), then adds middleware and calls MapRazorPages() on WebApplication. Its pipeline can include static files, HTTPS redirection, authorization, and environment-dependent error handling. section 13.1.2

