Skip to main content

Program.cs and the Host Builder

Level: Beginner

ℹ️ Where This Fits

Program.cs is the control room of an ASP.NET Core app. Learn it before middleware, routing, controllers, dependency injection, configuration, and authentication.

ℹ️ What You'll Learn
  • Program.cs structure: Builder → Configuration → Build → Middleware → Routes → Run
  • CreateBuilder(args): Creating builder, loading configuration files, environment setup
  • builder.Services.Add*(): Registering StudentService, AttendanceService, DbContext, Authentication
  • Service lifetimes: Transient vs Scoped vs Singleton (when to use each)
  • builder.Build(): Why you must build before configuring middleware and routes
  • app.Use*(): Adding middleware in correct order (Exception → HTTPS → Static → Routing → Auth → Custom)
  • app.Map*(): Mapping routes (MapGet, MapPost, MapPut, MapDelete for CRUD)
  • app.Run(): Starting web server and listening for HTTP requests
  • Configuration in Program.cs: Connection strings, logging levels, feature flags
  • School Management example: Wiring StudentService → DbContext → Routes together
  • Common mistakes: Registering services after Build(), wrong middleware order, forgetting app.Run()
  • Testing Program.cs: How to verify services are registered correctly

What is Program.cs?

Program.cs is the first file ASP.NET Core runs when your application starts.

When you run:

dotnet run

.NET starts your app from Program.cs.

In simple words:

Program.cs decides how the application starts, what services it has, how requests are processed, and which URLs are handled.

The Smallest Program.cs

💻 Try It — Console App
💡 This is the smallest useful ASP.NET Core app.⌥ GitHub
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

Four important steps happen here.

LineMeaning
CreateBuilder(args)Prepare configuration and services
builder.Build()Build the web application
MapGet(...)Map URL to C# code
Run()Start listening for requests

Step 1: CreateBuilder

var builder = WebApplication.CreateBuilder(args);

This creates a builder object. Think of it as preparing the application blueprint.

The builder knows about:

  • Configuration files
  • Logging
  • Environment
  • Services
  • Command-line arguments

Example:

dotnet run --urls=http://localhost:8080

The args part allows command-line values to be passed into the app.

Step 2: Register Services

Services are reusable classes your application needs.

Examples:

  • Student service
  • Teacher service
  • Attendance service
  • Database context
  • Email sender
  • Logging
  • Authentication

You register services before Build():

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<StudentService>();
builder.Services.AddScoped<AttendanceService>();

var app = builder.Build();

Later, ASP.NET Core can provide these services automatically where needed. This is called Dependency Injection.

Step 3: Build the App

var app = builder.Build();

This converts the builder blueprint into a real web application.

After this line, you usually configure:

  • Middleware
  • Routes
  • Controllers
  • Static files
  • Error handling

Step 4: Add Middleware

Middleware processes requests before they reach your route/controller.

app.UseExceptionHandler("/error");
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

Middleware order matters. ASP.NET Core runs middleware from top to bottom.

Step 5: Map Routes

Routes connect URLs to code.

app.MapGet("/", () => "Home");
app.MapGet("/students/{id}", (int id) => $"Student {id}");

When the browser requests /students/101, ASP.NET Core runs the matching handler and passes 101 as id.

Step 6: Run the App

app.Run();

This starts the web server.

After Run(), the app waits for HTTP requests until you stop it with Ctrl + C.

Complete SchoolPortal Example

var builder = WebApplication.CreateBuilder(args);

// Services
builder.Services.AddScoped<StudentService>();
builder.Services.AddScoped<AttendanceService>();

var app = builder.Build();

// Middleware
app.UseExceptionHandler("/error");

// Routes
app.MapGet("/", () => "Welcome to SchoolPortal");

app.MapGet("/students/{id}", (int id, StudentService service) =>
{
return service.GetStudentName(id);
});

app.MapPost("/attendance/{studentId}", (int studentId, AttendanceService service) =>
{
service.MarkPresent(studentId);
return "Attendance marked";
});

app.Run();

public class StudentService
{
public string GetStudentName(int id)
{
return $"Student {id}";
}
}

public class AttendanceService
{
public void MarkPresent(int studentId)
{
Console.WriteLine($"Marked present: {studentId}");
}
}

This example shows three major ideas:

PartMeaning
builder.Services.AddScopedRegister services
app.UseExceptionHandlerAdd middleware
app.MapGet / app.MapPostAdd routes

Request Flow from Program.cs

User opens /students/101
v
ASP.NET Core receives request
v
Middleware runs
v
Routing finds /students/{id}
v
StudentService is injected
v
Handler returns response
v
Browser receives response

Common Program.cs Sections

Most real projects follow this shape:

var builder = WebApplication.CreateBuilder(args);

// 1. Register services
builder.Services.AddControllers();
builder.Services.AddScoped<StudentService>();

var app = builder.Build();

// 2. Configure middleware
app.UseExceptionHandler("/error");
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

// 3. Map endpoints
app.MapControllers();

// 4. Start app
app.Run();

Common Beginner Mistakes

MistakeWhy It Is Wrong
Registering services after builder.Build()Services must be registered before the app is built
Placing app.Run() before routesCode after Run() will not be reached during normal startup
Wrong middleware orderAuth, routing, CORS, and errors may behave incorrectly
Putting too much business logic in Program.csReal apps should move logic into services/controllers
Not understanding builder vs appbuilder prepares; app runs

What to Remember

builder.Services = register tools/classes
app.Use... = add middleware
app.Map... = map URLs/endpoints
app.Run() = start web server
ℹ️ Beginner Rule

When you are confused, divide Program.cs into four sections: services, build, middleware, endpoints. That mental model will help in every ASP.NET Core project.

🎯 Interview Favourite

Q: What does Program.cs do in ASP.NET Core?

Good Answer: "Program.cs is the entry point of an ASP.NET Core application. It creates the application builder, registers services for dependency injection, builds the app, configures middleware, maps routes or controllers, and finally starts the web server using app.Run(). It is the central place where the application startup is configured."

Practice Before Next Article

  1. Add /students/{id} route.
  2. Add /teachers/{id} route.
  3. Add a StudentService class.
  4. Register StudentService using AddScoped.
  5. Explain the difference between builder.Services and app.MapGet.
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on ASP.NET Core Program.cs. Try these prompts:

  • "Explain Program.cs line by line"
  • "What is the difference between builder and app?"
  • "Why must services be registered before Build?"
  • "Give me a simple Program.cs for a school API"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

Next Article

-> How ASP.NET Core Handles Requests

nexcoding.in