Program.cs is the entry point for an ASP.NET Core application. It bootstraps the web application, registers services, and configures the HTTP request middleware pipeline. section 1.2.2 section 1.2.1
A typical Program.cs setup proceeds through these responsibilities:
- Create a WebApplicationBuilder, then use it to build the WebApplication instance. section 1.2.2
- Register services such as controllers, endpoint metadata, and Swagger generation through builder.Services. section 1.2.2
- Configure middleware, including development-only Swagger, HTTPS redirection, authorization, and controller mapping. section 1.2.2
- Call app.Run() to start the application; Run is terminal and is processed last. section 1.2.2
var builder = WebApplication.CreateBuilder(args); #1
// Add services to the container.
builder.Services.AddControllers(); #2
// Learn more about configuring Swagger/OpenAPI
// at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); #2
builder.Services.AddSwaggerGen(); #2
var app = builder.Build(); #3
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger(); #4
app.UseSwaggerUI(); #4
}
app.UseHttpsRedirection(); #4
app.UseAuthorization(); #4
app.MapControllers(); #4
app.Run(); #5
Use the annotated template to follow the setup sequence from builder creation through service registration, environment checks, middleware configuration, controller mapping, and application startup. section 1.2.2
Restricting Swagger to selected environments
A board-game API can use an app-setting value such as UseSwagger to decide whether Swagger middleware and its user interface are added. Updating Program.cs to apply that condition prevents Swagger from being enabled when the setting is false. section 2.5.3
ASP.NET Core naming conventions make configuration concise: service extensions commonly begin with Add, while middleware extensions use Use, Map, or Run. The minimal hosting model combines responsibilities formerly separated between Program.cs and Startup.cs. section 1.2.2 section 1.2.1
