TExcelTAD
Home › ASP.NET Core › Project Structure & Program.cs

Project Structure & Program.cs

A new dotnet new web project contains only a handful of files, and each has a clear job. Knowing them well makes every later lesson easier.

text
HelloApi/
├── HelloApi.csproj                 project file: SDK, target framework, packages
├── Program.cs                      the app's entry point: services + pipeline + endpoints
├── appsettings.json                configuration for every environment
├── appsettings.Development.json    overrides used only while developing
├── Properties/
│   └── launchSettings.json         how `dotnet run` / the IDE start the app locally
├── bin/  obj/                      build output (never commit these)
└── wwwroot/                        (optional) static files such as CSS, JS, images

The project file

xml
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>
Setting Meaning
Sdk="Microsoft.NET.Sdk.Web" The Web SDK: references the ASP.NET Core shared framework, so no NuGet package is needed for ASP.NET Core itself
TargetFramework net9.0 — the .NET version you build for
Nullable Turns on nullable reference type warnings
ImplicitUsings Adds common using directives to every file automatically

With the Web SDK, implicit usings include System, System.Linq, System.Collections.Generic, System.Threading.Tasks, System.Net.Http.Json, Microsoft.AspNetCore.Builder, Microsoft.AspNetCore.Http, Microsoft.AspNetCore.Routing, Microsoft.Extensions.DependencyInjection, Microsoft.Extensions.Configuration, Microsoft.Extensions.Hosting and Microsoft.Extensions.Logging. That is why Program.cs needs no using lines at all.

When you add a package, it appears as a <PackageReference>:

bash · try it yourself
$ dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 9.0.10
$ grep PackageReference HelloApi.csproj
info : Adding PackageReference for package 'Microsoft.EntityFrameworkCore.Sqlite' into project '/home/me/HelloApi/HelloApi.csproj'.
info : Writing assets file to disk. Path: /home/me/HelloApi/obj/project.assets.json
log  : Restored /home/me/HelloApi/HelloApi.csproj (in 1.42 sec).
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.10" />

Program.cs: two phases

Program.cs uses C# top-level statements and is always split into the same two phases:

csharp
// ---- Phase 1: configure the builder ----
var builder = WebApplication.CreateBuilder(args);   // loads config, logging, the host

builder.Services.AddSingleton<GreetingService>();   // register services for DI

// ---- Phase 2: configure the app ----
var app = builder.Build();                          // freezes the service list

if (app.Environment.IsDevelopment())
    app.UseDeveloperExceptionPage();               // middleware (runs for every request)

app.MapGet("/", (GreetingService greeter) => greeter.Greet("world"));  // endpoints

app.Run();                                          // start Kestrel and block

class GreetingService
{
    public string Greet(string name) => 
quot;Hello, {name}!"; }
  1. WebApplication.CreateBuilder(args) reads configuration (appsettings files, environment variables, command-line args), sets up logging and prepares the service collection.
  2. builder.Services is where you register everything your app needs: databases, your own classes, authentication…
  3. builder.Build() creates the WebApplication. After this point the service list is read-only.
  4. app.Use… calls add middleware; app.Map… calls add endpoints.
  5. app.Run() starts listening for requests.

Note: Type declarations such as class GreetingService must come after the top-level statements. In bigger apps you put them in their own files (Services/GreetingService.cs).

The builder pattern in plain C#

Why two phases? Registration must be finished before the first request arrives, so ASP.NET Core collects everything in a mutable builder and then produces an app that can no longer change its services. You can see the same pattern in ordinary C#:

csharp · try it yourself
using System;
using System.Collections.Generic;

var builder = new MiniAppBuilder();
builder.Services.Add("GreetingService");
builder.Services.Add("Clock");

var app = builder.Build();
app.Map("/", "Hello!");
app.Map("/about", "Built with the builder pattern");

app.Run();

class MiniAppBuilder
{
    public List<string> Services { get; } = new();
    public MiniApp Build() => new MiniApp(Services.AsReadOnly());
}

class MiniApp
{
    private readonly IReadOnlyList<string> services;
    private readonly Dictionary<string, string> endpoints = new();
    public MiniApp(IReadOnlyList<string> services) => this.services = services;

    public void Map(string path, string response) => endpoints[path] = response;

    public void Run()
    {
        Console.WriteLine(
quot;Services: {string.Join(", ", services)}"); foreach (var (path, response) in endpoints) Console.WriteLine(
quot;GET {path} -> {response}"); Console.WriteLine(
quot;Can add services now? {services is List<string>}"); } }
Services: GreetingService, Clock
GET / -> Hello!
GET /about -> Built with the builder pattern
Can add services now? False

launchSettings.json

This file is only used on your machine by dotnet run, Visual Studio and VS Code. It is not deployed.

json
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5132",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7181;http://localhost:5132",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

dotnet run uses the first profile; pick another with dotnet run --launch-profile https. You can change applicationUrl to http://localhost:5000 instead of passing --urls every time.

appsettings.json

json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Settings in appsettings.Development.json override these while the environment is Development. The Configuration lesson covers this in depth.

Test yourself

Which SDK attribute makes a project an ASP.NET Core project?

  1. Microsoft.NET.Sdk
  2. Microsoft.NET.Sdk.Web
  3. Microsoft.AspNetCore.App
  4. Microsoft.NET.Sdk.Razor

Where must you register services such as AddSingleton<T>()?

  1. On builder.Services, before builder.Build()
  2. On app, after app.Run()
  3. In launchSettings.json
  4. Inside each endpoint handler

Is Properties/launchSettings.json used in production?

  1. Yes, it sets the production port
  2. Yes, it replaces appsettings.json
  3. No, it only affects local development tooling
  4. Only inside Docker