ASP.NET Project Structure
Before writing pages, it helps to know what each file in a new project does.
Create a Razor Pages Project
Example
dotnet new webapp -o SchoolSite
cd SchoolSite
dotnet watchThe Files and Folders
| Item | What it is for |
|---|---|
Program.cs | The starting point: sets up services and the request pipeline |
Pages/ | Your Razor Pages (.cshtml files and their .cshtml.cs code) |
Pages/Shared/_Layout.cshtml | The shared layout: header, menu, footer |
wwwroot/ | Static files: CSS, JavaScript, images |
appsettings.json | Settings such as connection strings and logging |
Properties/launchSettings.json | Port numbers and settings for local running |
SchoolSite.csproj | The project file: .NET version and packages |
Only files inside wwwroot can be downloaded directly by the browser. Your C# code and settings stay private on the server.
Program.cs
This file has two parts. First you register services (things your app needs). Then you build the app and add middleware (steps every request passes through).
Example
var builder = WebApplication.CreateBuilder(args);
// 1. Register services
builder.Services.AddRazorPages();
var app = builder.Build();
// 2. Configure the request pipeline (middleware)
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();What is Middleware?
Think of middleware as checkpoints on a road. Each request passes through them in order:
UseHttpsRedirectionsendshttp://visitors tohttps://UseStaticFilesserves CSS, JS and images fromwwwrootUseRoutingfinds which page or endpoint matches the URLUseAuthorizationchecks if the user is allowed inMapRazorPagesruns the matching page
The order matters. For example, authorization must come after routing.
You can write your own simple middleware:
Example
app.Use(async (context, next) =>
{
Console.WriteLine($"Request: {context.Request.Path}");
await next();
});Request: / Request: /Privacy
This prints each requested path to the terminal.
appsettings.json
Settings live in JSON so you can change them without changing code:
Example
{
"Logging": {
"LogLevel": {
"Default": "Information"
}
},
"AllowedHosts": "*",
"SchoolName": "Workownix Institute"
}Read a setting in Program.cs:
Example
var schoolName = builder.Configuration["SchoolName"];
Console.WriteLine(schoolName);Workownix Institute
There is also appsettings.Development.json, which overrides values only while you develop on your computer.
Environments
ASP.NET Core knows if it runs in Development, Staging or Production. In Development you see detailed error pages; in Production visitors see a friendly error page instead. The environment comes from the ASPNETCORE_ENVIRONMENT setting.
Exercise
Exercise
Which folder holds CSS files and images that the browser can download?
