Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 52 ยท Getting Started

Your First Web App

Build your first ASP.NET Core app: create the builder, map an endpoint, start Kestrel, call it with HttpClient and shut it down cleanly with StopAsync.

Time to write a web server. A complete ASP.NET Core app needs only a handful of lines, and each line has a clear job: create a builder, build the app, map an endpoint, run. This lesson walks through those four steps, shows what each returns, and then runs the app and calls it, so you see real HTTP responses.

You already met the full picture in What Is ASP.NET Core?. Here we slow down and focus on the code you will type at the top of every project.

The four-step recipe

Every Program.cs in a minimal web app follows the same shape:

C#
var builder = WebApplication.CreateBuilder(args);   // 1. create the builder

// ... register services here ...

var app = builder.Build();                          // 2. build the app

app.MapGet("/", () => "Hello, world!");             // 3. map endpoints (and add middleware)

app.Run();                                          // 4. start the server and wait

This is the real shape of a template-generated app (read-only here, because it needs the dotnet CLI and the web SDK, which adds the using lines for you).

flowchart TD
    A["CreateBuilder(args)<br/>WebApplicationBuilder"] --> B["Register services<br/>builder.Services"]
    B --> C["Build()<br/>WebApplication"]
    C --> D["MapGet / Use...<br/>endpoints and middleware"]
    D --> E["Run()<br/>listen until shutdown"]

The lifecycle of a minimal web app: configure, build, describe the pipeline, run.

Let us look at each step.

Step 1: WebApplication.CreateBuilder

WebApplication.CreateBuilder(args) returns a WebApplicationBuilder already configured with sensible defaults: Kestrel as the server, configuration from appsettings.json, environment variables and the command line, console logging, and the dependency injection container. The args parameter lets the command line influence the configuration (for example --urls http://localhost:6000).

In top-level statements in a real project, args is available automatically. Our runner program has no command-line arguments, so we call CreateBuilder() without them, which works the same way.

Step 2: Build()

builder.Build() freezes the service container and returns a WebApplication. After this call you can no longer register services, only configure how requests are handled. Put the services before and the endpoints after, and you will never trip over this.

Step 3: MapGet and friends

app.MapGet(pattern, handler) declares an endpoint: when a GET request arrives whose path matches the pattern, run the handler and write its result to the response. A handler can be a lambda, a method group or a local function. There are matching methods for the other HTTP verbs: MapPost, MapPut, MapDelete, MapPatch. The minimal API endpoints lesson covers them all.

Step 4: Run()

app.Run() starts Kestrel and blocks until the app shuts down, for example when you press Ctrl+C. It is the last line in a real Program.cs. If you want to start the server and keep going, use await app.StartAsync() instead; we need that in our examples so the client code can run after the server starts.

Running it for real

Here is the complete program, with the server and a client. Read the code first, then press Run.

C# Hello, web

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Three lines are specific to our runner. ClearProviders() removes the console logger so request logs do not mix with our output. UseUrls("http://127.0.0.1:0") binds to the loopback address with a free port chosen by the operating system. app.Urls.First() reads back the real address once the server has started.

Why not call app.Run() here? It blocks forever, and our program must finish. StartAsync returns as soon as Kestrel is listening, and StopAsync shuts it down gracefully. On your own machine, use app.Run().

What the server sends back

A returned string becomes a text/plain response with status 200 OK. But the framework does much more than that. Let us look at the whole response, including a request for a path that nobody mapped.

C# Inspecting responses and a 404

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the output line by line:

  • / returns 200 with text/plain.
  • /data returns an object, which ASP.NET Core serializes to JSON (application/json) with camelCase property names.
  • /missing returns 404 Not Found with an empty body: no endpoint matched, so the default response applies.
  • A POST to / returns 405 Method Not Allowed: the path exists, but only for GET. Routing knows the difference between "no such path" and "wrong verb".

You did not write any of that error handling. The routing system produces the right status codes for you.

Return values at a glance

What your lambda returns decides what the client sees. This table covers the first cases you will use; Responses, Results and Content Negotiation goes deeper.

Handler returns Response
string 200, text/plain
An object or record 200, application/json
int, bool, double 200, the value as text
Results.NotFound() 404, empty body
Results.Ok(value) 200, JSON
Task<T> the same, once the task completes
void 200, empty body

Making endpoints asynchronous

Real handlers read from databases and call other services, so they are async. Marking a lambda async and returning a value works exactly as you expect; the framework awaits it.

C# An async endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

While Task.Delay is waiting, the server thread is free to handle other requests. That is why you should never block with .Result or Thread.Sleep inside a handler: you would hold a thread hostage for the whole wait. The async/await lesson explains why.

Common mistakes

  • Calling MapGet before Build(). MapGet lives on the built WebApplication, not the builder. If the compiler says WebApplicationBuilder has no MapGet, you forgot a line.
  • Registering services after Build(). The container is already frozen, so register services on builder.Services first.
  • Forgetting that Run() blocks. Code after app.Run() executes only after shutdown.
  • A handler that throws. If a handler throws an exception and nothing handles it, the client gets 500 Internal Server Error. Error handling shows how to turn that into helpful responses.
  • Hard-coded ports. Real apps read addresses from configuration or launchSettings.json, so the same code runs everywhere.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the correct order of the four steps in a minimal web app?

    You create the builder, build the app, map endpoints on the built app, then run. Services are registered between the first and second step.
  2. 2. Which call starts the server and returns immediately instead of blocking?

    StartAsync returns once Kestrel is listening. Run blocks until shutdown.
  3. 3. A client sends POST / but only MapGet("/", ...) exists. What status does the framework return?

    The path matches an endpoint, but not for that HTTP method, so routing answers 405.
  4. 4. What does a lambda that returns an anonymous object produce by default?

    Objects are serialized with System.Text.Json using web defaults, producing application/json.

Summary

  • A minimal web app is four steps: CreateBuilder, Build, map endpoints, Run.
  • Register services on the builder before Build(); map endpoints and add middleware on the app afterwards.
  • MapGet, MapPost and friends bind a URL pattern and verb to a handler.
  • Strings become text/plain, objects become JSON, unknown paths give 404 and wrong verbs give 405.
  • Handlers may be async; never block a thread inside them.
  • In our examples StartAsync, HttpClient and StopAsync replace Run() and the browser.

Next: Anatomy of a Project