The startup flow is the most critical 500ms of any application. For an expert architect, understanding this sequence is mandatory for debugging initialization errors and optimizing performance.
In modern .NET Core (6.0+), the startup code is cleaner. We use Top-Level Statements, which means the compiler implicitly wraps your code in a static Main method. This is the official entry point for the process.
WebApplication.CreateBuilder() initializes the host, loading configurations from appsettings.json and environment variables.
Registering dependencies (DB, Identity, MVC) in the IServiceCollection (Dependency Injection container).
builder.Build() locks the DI container and creates the WebApplication instance.
After building the app, we define the **HTTP Request Pipeline** using the app.Use... methods. Order is everything! For example, Authentication MUST come before Authorization—otherwise, your security is broken!
// 1. SERVICES (The What)
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<AppDbContext>();
var app = builder.Build();
// 2. MIDDLEWARE (The How)
if (!app.Environment.IsDevelopment()) {
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}");
app.Run(); // 3. EXECUTION
For high-traffic, low-latency apps, senior architects avoid doing "Heavy Database Queries" inside the startup flow. Instead, they use Background Tasks or **Lazy Initialization** to ensure that the server starts in milliseconds, preventing "Request Timeout" errors during scaling events or server reboots.