Written by Mark Pringle | Last Updated on Saturday, November 05, 2022

Visual Studio ASP.NET Version: 6.0 General Information

The Program.cs file in a .NET Core 6 project is the application's entry point. It is where the web application is created and built, routing is configured, services are added, and the HTTP request pipeline is configured. This is where you register middleware, authentication, and add DbContext.

Before version 6 of ASP.NET Core, there was a Startup.cs and Program.cs file. However, in .Net 6, the Startup.cs class has been removed. Microsoft unified Startup.cs and Program.cs into Program.cs.

A typical Program.cs file that Visual Studio generates might look like this.

using DemoProject.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();

app.Run();