Day 10: ASP.NET Core Architecture
Welcome to Day 10. We are leaving pure console applications behind. Welcome to the Web.
ASP.NET Core is Microsoftâs high-performance, open-source, cross-platform framework for building modern, cloud-enabled web applications. It is consistently ranked as one of the fastest web frameworks on the planet.
Setup
Instead of a console app, generate a web API blank slate in your terminal:
dotnet new web -n MyFirstApi
cd MyFirstApi
Open Program.cs. Notice itâs remarkably small! This is the modern Minimal API structure.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Run dotnet run. It will host a local server. Navigate to http://localhost:<port> in your browser, and youâll see âHello World!â.
The Anatomy of an ASP.NET App
There are three major phases to the ASP.NET Core startup file (Program.cs):
1. The Builder (Services)
WebApplication.CreateBuilder establishes the environment (development, production), configuration (appsettings.json), and logging.
Itâs also where you register Services (like Database connections, CORS, Auth rules) into the Dependency Injection container.
2. The App (Middleware Pipeline)
Once builder.Build() is called, you have the app. You use this to configure the HTTP Request Pipeline.
When a browser sends an HTTP Request to your server, it passes through a series of Middleware components before hitting your actual endpoints.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// MIDDLEWARE PIPELINE STARTS HERE:
// 1. Catches global crash errors
app.UseExceptionHandler("/error");
// 2. Redirects HTTP to HTTPS
app.UseHttpsRedirection();
// 3. Authenticates the user (Who are you?)
app.UseAuthentication();
// 4. Authorizes the user (Are you allowed here?)
app.UseAuthorization();
3. The Endpoints
At the end of the pipeline sit your endpoints (your actual application logic). If the request makes it through all the middleware, the endpoint processes it and fires the HTTP Response back through the pipeline to the client!
app.MapGet("/api/status", () => "Server is running perfectly.");
app.Run(); // Start the server, sit, and listen for traffic.
What is Middleware?
Think of middleware like an assembly line.
A request comes in. Middleware 1 logs the time and hands it to Middleware 2. Middleware 2 checks if thereâs an API Key. If there isnât, Middleware 2 short-circuits the pipeline, rejecting the request instantly with a 401 Unauthorized without letting it hit the database endpoints.
Order matters! You must put UseAuthentication() BEFORE UseAuthorization().
Challenge for Day 10
Create a new dotnet new web project. Add an endpoint app.MapGet("/ping", () => "pong");. Run the application and hit both / and /ping in your browser!
Tomorrow: Dependency Injection (DI).