Program.cs is the ASP.NET Core application entry point. Its statements run at startup to configure the platform and the application. Modern projects use top-level statements here rather than a separate Startup class; a project cannot have top-level statements in more than one file. section 12.3.1 section 5.2
The usual startup sequence is:
- Call WebApplication.CreateBuilder(args) to establish basic platform features, including configuration, logging, and the Kestrel HTTP server. section 12.3.1
- Register services on builder.Services before calling builder.Build(). For example, AddControllersWithViews supplies services for MVC controllers and Razor views. section 7.1.5
- Use the resulting app to configure request handling, then call app.Run() to start listening for HTTP requests. section 12.3.1
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
A minimal Program.cs maps GET requests for / to a string response. It shows the builder, app, endpoint, and Run call without MVC setup. section 12.3.1
In an MVC application, app.UseStaticFiles() enables files under wwwroot, while app.MapDefaultControllerRoute() registers controller endpoints using a default routing convention. The request pipeline passes HTTP requests through middleware that can inspect or change requests and responses; endpoint routing is added automatically. section 7.1.5
Program.cs also grows with the application. Entity Framework Core services can be registered with a connection string read from configuration, and startup code can resolve a DataContext to seed a database. Blazor Server requires its services and hub endpoint alongside controller and Razor Pages registrations. section 32.2.2 section 33.3.1
Listing 33.3 Configuring the application in the Program.cs file in the Advanced folder
using Microsoft.EntityFrameworkCore;
using Advanced.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddDbContext<DataContext>(opts => {
opts.UseSqlServer(
builder.Configuration["ConnectionStrings:PeopleConnection"]);
opts.EnableSensitiveDataLogging(true);
});
var app = builder.Build();
app.UseStaticFiles();
app.MapControllers();
app.MapControllerRoute("controllers",
"controllers/{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.MapBlazorHub();
var context = app.Services.CreateScope().ServiceProvider
.GetRequiredService<DataContext>();
SeedData.SeedDatabase(context);
app.Run();
A fuller Program.cs puts MVC, Razor Pages, Blazor Server, and database service registrations before Build; static-file and endpoint setup follows it. section 33.3.1
