WebApplication is the built ASP.NET Core application object that connects service configuration, request endpoints, middleware, and server execution. A typical Program.cs creates a WebApplicationBuilder, registers services, calls Build, configures the resulting WebApplication, and calls Run. section 12.3.1
Minimal request pipeline
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run(); CreateBuilder sets up configuration, logging, and the Kestrel HTTP server. Build finalizes application setup. MapGet registers a handler for the root path, and Run starts listening for requests. section 12.3.1
The application implements IEndpointRouteBuilder, so endpoint-mapping extensions such as MapGet can be called directly on it. Middleware is also configured on the WebApplication, allowing built-in or custom components to process requests when endpoint mappings are not enough. section 12.3.1 section 14.5.2
Use the WebApplication properties according to where application setup occurs:
- Read app.Configuration while configuring the pipeline, or use builder.Configuration while registering services. section 15.2.3
- Read app.Environment for pipeline decisions; use builder.Environment when service registration depends on the environment. section 14.5.2 section 15.2.6
- Inject IConfiguration or IWebHostEnvironment into middleware and endpoint handlers when request-time access is needed. section 15.2.6
Environment-specific setup
var builder = WebApplication.CreateBuilder(args); var env = builder.Environment; if (env.IsDevelopment()) { builder.Services.AddScoped<IResponseFormatter, TimeResponseFormatter>(); } else { builder.Services.AddScoped<IResponseFormatter, HtmlResponseFormatter>(); } var app = builder.Build(); app.UseMiddleware<WeatherMiddleware>(); app.MapGet("/config", (IConfiguration config) => $"The config setting is: {config["Logging:LogLevel:Default"]}"); app.Run(); This pattern selects services before Build, configures middleware afterward, and exposes configuration through an endpoint.
HTTP/1.1 200 OK Transfer-Encoding: chunked Content-Type: text/plain; charset=utf-8 Date: Wed, 14 Dec 2022 08:09:13 GMT Server: Kestrel
A request to the running application produces a normal HTTP response, including a 200 status, text content type, and Kestrel server header. section 12.3.1

