ASP.NET Core Project Anatomy: Program.cs and Middleware
Since .NET 6, ASP.NET Core uses a streamlined, minimal hosting model consolidated in Program.cs. Understanding the two phases—Service Registration and Middleware Pipeline Configuration—is critical.
1. The Anatomy of Program.cs
var builder = WebApplication.CreateBuilder(args);
// -------------------------------------------------------------
// 1. Configure Services (Dependency Injection Container)
// -------------------------------------------------------------
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Add Database Context
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Add CORS Policy for Angular client
builder.Services.AddCors(options =>
{
options.AddPolicy("AngularDev", policy =>
{
policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
var app = builder.Build();
// -------------------------------------------------------------
// 2. Configure HTTP Request Pipeline (Middleware Order Matters!)
// -------------------------------------------------------------
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AngularDev");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
2. The Critical Middleware Order
Middleware executes in the exact order it is registered:
1. UseExceptionHandler (Must catch all downstream errors)
2. UseHttpsRedirection
3. UseRouting
4. UseCors (Must precede Authentication/Authorization)
5. UseAuthentication
6. UseAuthorization
7. MapControllers

