ASP.NET Core is built from the ground up to be modular and blazing fast. At its core is Kestrel, an asynchronous, event-driven HTTP server powered by Libuv and native sockets, capable of handling millions of concurrent requests.
1. The Anatomy of Program.cs in .NET 8
Every ASP.NET Core application follows a two-phase initialization lifecycle:
// =========================================================================
// PHASE 1: Dependency Injection & Configuration (WebApplicationBuilder)
// =========================================================================
var builder = WebApplication.CreateBuilder(args);
// Read configuration from appsettings.json, environment variables, or CLI
var dbConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
// Register application services into the IoC container
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IOrderService, OrderService>();
// Build the application instance
var app = builder.Build();
// =========================================================================
// PHASE 2: Middleware Pipeline (WebApplication)
// The ORDER OF MIDDLEWARE MATTERS CRITICALLY!
// =========================================================================
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}
else
{
app.UseExceptionHandler("/error");
app.UseHsts(); // HTTP Strict Transport Security
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication(); // 1. Who is the user?
app.UseAuthorization(); // 2. What are they allowed to do?
// Map Route Endpoints
app.MapGet("/health", () => Results.Ok(new { Status = "Healthy", Timestamp = DateTime.UtcNow }));
app.Run();