A minimal API
ASP.NET Core builds an HTTP server into a console program. A minimal API is the shortest form: a builder, a few endpoint registrations, and Run. The server here listens on a loopback port, calls itself with an HttpClient so that the page has real output, and stops.
The builder and the app
WebApplication.CreateBuilder reads the command line and the environment, and gives a builder with a logging system, a configuration and dependency injection. Build makes the app, which is also the host that runs it:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http.Json;
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://127.0.0.1:5099");
builder.Logging.SetMinimumLevel(LogLevel.Warning);
var app = builder.Build();
app.MapGet("/orders/{id:int}", (int id) => Results.Json(new { id, total = id * 1.5m }));
app.MapPost("/orders", (Order order) => Results.Created($"/orders/{order.Id}", order));
var run = app.RunAsync();
using var client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5099") };
for (var attempt = 0; attempt < 40; attempt++)
{
try
{
var probe = await client.GetAsync("/orders/1");
if (probe.IsSuccessStatusCode)
{
break;
}
}
catch (HttpRequestException)
{
}
await Task.Delay(50);
}
var response = await client.GetAsync("/orders/42");
Console.WriteLine($"status {(int)response.StatusCode}");
Console.WriteLine(await response.Content.ReadAsStringAsync());
var missing = await client.GetAsync("/nothing");
Console.WriteLine($"missing {(int)missing.StatusCode}");
var created = await client.PostAsJsonAsync("/orders", new Order(7, 21.0m));
Console.WriteLine($"created {(int)created.StatusCode}");
Console.WriteLine(await created.Content.ReadAsStringAsync());
await app.StopAsync();
await run;
internal sealed record Order(int Id, decimal Total);
dotnet run
status 200
{"id":42,"total":63.0}
missing 404
created 201
{"id":7,"total":21.0}
The app answered a GET with a JSON object, a GET of an unknown route with 404, and a POST with 201 and the object it was given. The two calls are the whole contract of a small service, and the program is a console app: the same code runs on a server with a different address and no client in it.
MapGet and MapPost
- The route template is a string with parameters in braces. {id:int} is a constraint: a request with a non-numeric id does not match the route and gets 404, not an exception.
- The lambda receives the parameters the route declares and the services the app has, and its return value is the response. A record parameter of a POST is read from the JSON body with the serializer of the app.
- Results.Json writes an object as JSON, Results.Created adds a status and a location, and Results.Ok is the plain 200.
- A route may return Results.NotFound(), Results.BadRequest() or a typed result; all of them implement IResult.
A client in the same program
app.RunAsync() starts the server and returns a task that completes when the server stops, so the program keeps a reference to it and calls StopAsync when the calls are done. PostAsJsonAsync serializes the record and sets the content type; ReadAsStringAsync returns the body as text, which is how the JSON reaches the page.
The loop before the first call is not decoration: the server binds its port asynchronously, and a client that connects a millisecond too early gets HttpRequestException. A real client retries with a bound and a delay, which is what the loop does; forty attempts of fifty milliseconds is two seconds.
Kestrel and the addresses
Kestrel is the HTTP server inside ASP.NET Core, and it runs on Linux without a reverse proxy. UseUrls sets the addresses; http://127.0.0.1:5099 is a loopback port, so nothing outside the container can connect. A service listens on http://0.0.0.0:8080 and is published behind a proxy that terminates TLS, which is the usual deployment and the one the Docker page of the modern project group describes.
The shared framework supplies the server and the routing, so the project file adds one item and no package:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
A web project generated by dotnet new web uses the Microsoft.NET.Sdk.Web SDK instead, which adds the same reference and the wwwroot conventions. The full framework, MVC, Razor pages and Blazor, is the subject of its own course, which is being prepared.
Exercises
- Add /health that returns Results.Ok("up") and call it.
- Change the route constraint to {id:alpha} and call it with a number.
- Return Results.NotFound() for an id above a hundred and read the status.
- Start the same app with ASPNETCORE_URLS instead of UseUrls and find which one wins.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which call creates the builder of a minimal API?
Answer
WebApplication.CreateBuilder(args)
The builder carries logging, configuration and services; Build makes the app.
-
What does MapGet register?
Answer
A handler for GET requests on a route template
The template with braces declares the route parameters.
-
What does the constraint {id:int} do?
Answer
Matches only a numeric id, otherwise the route does not match
A non-numeric path does not match, so the app answers 404.
-
What status does Results.Created send?
Answer
201
The measured POST printed created 201.
-
What does app.RunAsync return?
Answer
A task that completes when the server stops
The program awaited it after StopAsync.
-
Why does the program call StopAsync before awaiting RunAsync?
Answer
To end the server cleanly instead of waiting for ever
RunAsync stays pending while the server listens.
-
How is a record parameter of MapPost filled?
Answer
From the JSON body, deserialized by the app
The measured POST sent the record as JSON and the handler returned it.
-
What is Kestrel?
Answer
The HTTP server inside ASP.NET Core
It listens on the addresses the app configures and runs on Linux.
-
Why does the client loop before the first request?
Answer
The server binds its port asynchronously
An early connection fails, so the client retries for a bounded time.
-
Which reference makes the ASP.NET Core types available to a console project?
Answer
FrameworkReference to Microsoft.AspNetCore.App
The shared framework is installed here, so the build stays offline.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev