Your first ASP.NET Core app

ASP.NET Core · Essentials · 10 min

Every ASP.NET Core service starts from this same small Program.cs structure.

Create an app with dotnet new web -o Api (an empty app) or dotnet new webapi (with OpenAPI and a sample endpoint), then dotnet run or dotnet watch for hot reload. The app listens on the URLs from Properties/launchSettings.json, such as http://localhost:5000.

Program.cs has two phases:

  • Build: var builder = WebApplication.CreateBuilder(args); sets up configuration (appsettings.json, environment variables, command line), logging and the dependency injection container. You register services on builder.Services.
  • Run: var app = builder.Build(); creates the app. You add middleware (app.UseX()) and endpoints (app.MapGet(...)), then app.Run() starts the web server and blocks until shutdown.

The server is Kestrel, a cross-platform, high-performance HTTP server built into the framework. In production it can face the internet directly or sit behind a reverse proxy such as Nginx, IIS or a cloud load balancer.

The project uses the Microsoft.NET.Sdk.Web SDK, which references the whole ASP.NET Core shared framework, so no extra packages are needed for routing, JSON, DI, logging or configuration.

The environment (ASPNETCORE_ENVIRONMENT: Development, Staging, Production) changes behavior such as detailed error pages and which appsettings file is loaded; check it with app.Environment.IsDevelopment().

Example

// Program.cs (dotnet new web -o Api && cd Api && dotnet run)
var builder = WebApplication.CreateBuilder(args);
// register services here: builder.Services.Add...

var app = builder.Build();
// add middleware and endpoints here
app.MapGet("/", () => "Hello World!");
app.MapGet("/env", (IWebHostEnvironment env) => env.EnvironmentName);

app.Run();   // starts Kestrel and blocks until shutdown

// $ curl http://localhost:5000/      -> Hello World!
// $ curl http://localhost:5000/env   -> Development

Remember

  • CreateBuilder sets up config, logging and DI; Build creates the app
  • Register services before Build, add middleware and endpoints after
  • Kestrel is the built-in web server
  • ASPNETCORE_ENVIRONMENT selects Development/Production behavior

Watch out for

  • Trying to register services on builder.Services after builder.Build() has been called.

Check yourself

  1. Where do you register services such as a database context?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis