Web frameworks · Intermediate · 24 min
Build a minimal API with ASP.NET Core in .NET 10
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · .NET 10 LTS SDK 10.0.404 (runtime 10.0.15, C# 14) · Microsoft.AspNetCore.OpenApi and Mvc.Testing 10.0.15 · the xUnit packages the SDK 10.0.404 xunit template adds · mcr.microsoft.com/dotnet/sdk:10.0
You will build a to-do API with ASP.NET Core minimal APIs on .NET 10 LTS, with route groups, typed results, built-in validation, ProblemDetails errors, an OpenAPI document and xUnit tests that run the whole app in memory.
On this page
ASP.NET Core has two ways to write HTTP APIs: controllers, which group actions into classes, and minimal APIs, where each endpoint is a lambda mapped to a route. Minimal APIs have caught up on the things that used to push teams towards controllers. In .NET 10 they validate request bodies with the same [Required] and [StringLength] attributes, produce an OpenAPI document without a third-party package, and describe their own responses through typed results.
You will build a to-do API with all five HTTP verbs. Requests are checked before your code runs, every error comes back in the same ProblemDetails shape, and an xUnit project starts the whole app in memory to test it. The data lives in a service you register with dependency injection, so you could later replace it with a database without touching the endpoints.
The tutorial pins .NET 10, the long-term support (LTS) release. .NET 11 is out as a standard-term (STS) release, and on today's dates both are supported until 14 November 2028. The LTS is what most libraries, hosting images and Linux distribution packages (including Ubuntu 26.04's dotnet-sdk-10.0) target first, and upgrading later is a one-line change to TargetFramework.
Keep error bodies small and predictable: many people will call an API like this from a low-end Android phone on prepaid data, where a short JSON error is cheaper to download and easier for the app to show than an HTML error page.
Step 1 · Create the solution and the web project
Check the SDK first. The number should start with 10.0:
dotnet --versionMake a throwaway folder with a solution file and an empty web project. dotnet new web is the smallest ASP.NET Core template: one Program.cs, no controllers, no sample weather endpoint. On .NET 10, dotnet new sln writes the newer XML-based .slnx format:
mkdir -p ~/todo-api-demo
cd ~/todo-api-demo
dotnet new sln -n TodoApi
dotnet new web -o TodoApi
dotnet sln add TodoApiThe template picks a random port. Replace its launch settings with a single http profile on port 5080 so the commands in this tutorial match your machine:
cat > TodoApi/Properties/launchSettings.json <<'JSON'
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": false,
"applicationUrl": "http://localhost:5080",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
JSONOpen a second terminal and start the app. dotnet run builds the project, uses the http profile and keeps running until you press Ctrl+C:
cd ~/todo-api-demo/TodoApi
dotnet runBack in the first terminal:
curl -s http://localhost:5080/
echoCheck it worked
The second terminal prints Now listening on: http://localhost:5080 and Hosting environment: Development. The curl call prints Hello World!. ls ~/todo-api-demo shows TodoApi and TodoApi.slnx.
Step 2 · Put the to-dos behind a service
Endpoints should not own the data. Write the record types and a small store, and hide the store behind an interface so the endpoints only know what it can do, not how it keeps things.
TodoInput is what a client sends; Todo is what the API returns, with the Id the server assigns. Keep them separate so a client can never choose its own ID:
cd ~/todo-api-demo/TodoApi
cat > TodoInput.cs <<'CS'
public record TodoInput(string Title, bool Done = false);
CS
cat > Todos.cs <<'CS'
using System.Collections.Concurrent;
public record Todo(int Id, string Title, bool Done);
public interface ITodoStore
{
IReadOnlyList<Todo> All();
Todo? Find(int id);
Todo Add(TodoInput input);
Todo? Update(int id, TodoInput input);
bool Remove(int id);
}
public class InMemoryTodoStore : ITodoStore
{
private readonly ConcurrentDictionary<int, Todo> _items = new();
private int _lastId;
public IReadOnlyList<Todo> All() => _items.Values.OrderBy(t => t.Id).ToList();
public Todo? Find(int id) => _items.GetValueOrDefault(id);
public Todo Add(TodoInput input)
{
var todo = new Todo(Interlocked.Increment(ref _lastId), input.Title.Trim(), input.Done);
_items[todo.Id] = todo;
return todo;
}
public Todo? Update(int id, TodoInput input)
{
if (!_items.ContainsKey(id)) return null;
var todo = new Todo(id, input.Title.Trim(), input.Done);
_items[id] = todo;
return todo;
}
public bool Remove(int id) => _items.TryRemove(id, out _);
}
CSASP.NET Core serves requests on many threads at once, which is why the store uses ConcurrentDictionary and Interlocked.Increment rather than a plain Dictionary and _lastId++.
Now register the store in Program.cs. AddSingleton means one instance for the life of the app, which is what an in-memory store needs: a scoped or transient store would forget every to-do at the end of each request.
cat > Program.cs <<'CS'
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ITodoStore, InMemoryTodoStore>();
var app = builder.Build();
app.MapGet("/", () => "Todo API");
app.Run();
CS
dotnet buildCheck it worked
dotnet build ends with Build succeeded and 0 Error(s). If it reports CS0246 for ITodoStore, check the file names: both .cs files must sit in ~/todo-api-demo/TodoApi, next to Program.cs.
Step 3 · Map the endpoints with a route group and typed results
Five endpoints share the /todos prefix. A route group lets you write the prefix once and attach settings, such as an OpenAPI tag, to all of them.
Each handler asks for ITodoStore as a parameter. Minimal APIs see that the type is a registered service and pass in the singleton; int id comes from the route and TodoInput input from the JSON body.
TypedResults.Ok(todo) returns an Ok<Todo> rather than a plain IResult. When a handler can answer in two ways, the return type Results<Ok<Todo>, NotFound> lists both, the compiler stops you returning anything else, and the OpenAPI document in a later step reads the possible responses straight from that type.
cat > TodoEndpoints.cs <<'CS'
using Microsoft.AspNetCore.Http.HttpResults;
public static class TodoEndpoints
{
public static RouteGroupBuilder MapTodos(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/todos").WithTags("Todos");
group.MapGet("/", (ITodoStore store) => TypedResults.Ok(store.All()));
group.MapGet("/{id:int}", Results<Ok<Todo>, NotFound> (int id, ITodoStore store) =>
store.Find(id) is { } todo ? TypedResults.Ok(todo) : TypedResults.NotFound());
group.MapPost("/", (TodoInput input, ITodoStore store) =>
{
var todo = store.Add(input);
return TypedResults.Created($"/todos/{todo.Id}", todo);
});
group.MapPut("/{id:int}", Results<Ok<Todo>, NotFound> (int id, TodoInput input, ITodoStore store) =>
store.Update(id, input) is { } todo ? TypedResults.Ok(todo) : TypedResults.NotFound());
group.MapDelete("/{id:int}", Results<NoContent, NotFound> (int id, ITodoStore store) =>
store.Remove(id) ? TypedResults.NoContent() : TypedResults.NotFound());
return group;
}
}
CS
cat > Program.cs <<'CS'
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ITodoStore, InMemoryTodoStore>();
var app = builder.Build();
app.MapGet("/", () => "Todo API");
app.MapTodos();
app.Run();
CSThe :int in {id:int} is a route constraint: /todos/abc does not match the route at all, so your handler never sees a value it cannot parse.
Stop the app in the second terminal with Ctrl+C and run dotnet run again so it picks up the new code.
Create two to-dos, list them, update the first, delete the second and read it back:
curl -s -X POST http://localhost:5080/todos -H 'Content-Type: application/json' -d '{"title":"Top up data bundle"}'
echo
curl -s -X POST http://localhost:5080/todos -H 'Content-Type: application/json' -d '{"title":"Pay electricity token"}'
echo
curl -s http://localhost:5080/todos
echo
curl -s -X PUT http://localhost:5080/todos/1 -H 'Content-Type: application/json' -d '{"title":"Top up data bundle","done":true}'
echo
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://localhost:5080/todos/2
curl -s -o /dev/null -w '%{http_code}\n' http://localhost:5080/todos/2Check it worked
The two POST calls answer {"id":1,"title":"Top up data bundle","done":false} and the same shape with "id":2. The list holds both, the PUT answers with "done":true, the DELETE prints 204 and reading the deleted to-do prints 404. The property names are camelCase because ASP.NET Core's JSON defaults convert Title to title in both directions.
Step 4 · Turn on validation for request bodies
The API accepts anything right now. Send an empty title, then a body with no title at all:
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:5080/todos -H 'Content-Type: application/json' -d '{"title":""}'
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:5080/todos -H 'Content-Type: application/json' -d '{"done":true}'The first stores a to-do with no title and prints 201. The second sends null into input.Title.Trim() and fails with a 500. Both are your bug, not the client's.
.NET 10 can check request bodies, query strings and headers against DataAnnotations attributes before your handler runs. Put the rules on the record's parameters:
cat > TodoInput.cs <<'CS'
using System.ComponentModel.DataAnnotations;
public record TodoInput(
[Required, StringLength(120, MinimumLength = 1)] string Title,
bool Done = false);
CSThen add one line to Program.cs. AddValidation turns on a source generator that finds every class or record your endpoints accept and writes the checking code at build time:
cat > Program.cs <<'CS'
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ITodoStore, InMemoryTodoStore>();
builder.Services.AddValidation();
var app = builder.Build();
app.MapGet("/", () => "Todo API");
app.MapTodos();
app.Run();
CSRestart the app with Ctrl+C and dotnet run, then send the same two requests and one title that is too long:
curl -s -X POST http://localhost:5080/todos -H 'Content-Type: application/json' -d '{"title":""}'
echo
curl -s -X POST http://localhost:5080/todos -H 'Content-Type: application/json' -d '{"done":true}'
echo
long=$(printf 'x%.0s' $(seq 1 130))
curl -s -X POST http://localhost:5080/todos -H 'Content-Type: application/json' -d "{\"title\":\"$long\"}"
echoCheck it worked
Each call answers with a 400 body that starts {"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"Title":[...]}. The first two say The Title field is required. and the third names the 1 to 120 character limit. The messages are English by default. If your users read French, Swahili or Hausa, translate them in the client using the errors keys, which stay the same whatever the language.
Step 5 · Return every error as ProblemDetails
Validation errors now have a standard shape, but other failures do not. A missing to-do returns a 404 with an empty body, malformed JSON and unhandled exceptions return a different shape again. ProblemDetails (RFC 9457) is one JSON format for all of them, with type, title, status and optional extra fields, and the response's Content-Type is application/problem+json.
Three pieces turn it on:
AddProblemDetailsregisters the service that writes the format.UseExceptionHandlercatches unhandled exceptions and writes a ProblemDetails body with no stack trace in it.StatusCodeSelectorkeeps a client mistake a client mistake: aBadHttpRequestException, which minimal APIs throw for malformed JSON, keeps its own400instead of becoming a500.UseStatusCodePagesfills in a body for error responses that have none, such asTypedResults.NotFound().
The /debug/fail endpoint exists only in Development, so you can see what an unhandled exception looks like. ExcludeFromDescription keeps it out of the OpenAPI document you add next.
cat > Program.cs <<'CS'
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ITodoStore, InMemoryTodoStore>();
builder.Services.AddValidation();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler(new ExceptionHandlerOptions
{
StatusCodeSelector = ex => ex is BadHttpRequestException bad
? bad.StatusCode
: StatusCodes.Status500InternalServerError
});
app.UseStatusCodePages();
if (app.Environment.IsDevelopment())
{
app.MapGet("/debug/fail", () => { throw new InvalidOperationException("Test failure"); })
.ExcludeFromDescription();
}
app.MapGet("/", () => "Todo API");
app.MapTodos();
app.Run();
CSRestart the app, then ask for a to-do that does not exist, send broken JSON and call the failing endpoint. -i shows the headers, and grep keeps the status line, the content type and the body:
curl -s -i http://localhost:5080/todos/999 | grep -iE '^HTTP|^content-type|^\{'
curl -s -i -X POST http://localhost:5080/todos -H 'Content-Type: application/json' -d '{"title":' | grep -iE '^HTTP|^content-type|^\{'
curl -s -i http://localhost:5080/debug/fail | grep -iE '^HTTP|^content-type|^\{'Check it worked
All three responses have Content-Type: application/problem+json. The first is 404 with "title":"Not Found", the second 400 with "title":"Bad Request" and the third 500 with "title":"An error occurred while processing your request.". Each body has a traceId you can search for in the app's log. The text Test failure appears in the second terminal's log, not in the response, so internal details stay on your server.
Step 6 · Publish an OpenAPI document
An OpenAPI document describes every route, parameter and response in a file other tools can read: client generators, API explorers and contract tests. ASP.NET Core 10 builds it from your endpoints at run time. Add the package with an exact version:
dotnet add package Microsoft.AspNetCore.OpenApi --version 10.0.15Register the generator and map the document. Like the failing endpoint, the document is only served in Development; in production you can publish it on purpose or generate it at build time instead.
cat > Program.cs <<'CS'
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ITodoStore, InMemoryTodoStore>();
builder.Services.AddValidation();
builder.Services.AddProblemDetails();
builder.Services.AddOpenApi();
var app = builder.Build();
app.UseExceptionHandler(new ExceptionHandlerOptions
{
StatusCodeSelector = ex => ex is BadHttpRequestException bad
? bad.StatusCode
: StatusCodes.Status500InternalServerError
});
app.UseStatusCodePages();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapGet("/debug/fail", () => { throw new InvalidOperationException("Test failure"); })
.ExcludeFromDescription();
}
app.MapGet("/", () => "Todo API");
app.MapTodos();
app.Run();
CSRestart the app and save the document to ~/todo-api-demo/openapi.json, then read its start and list the route paths in it:
cd ~/todo-api-demo
curl -s -o openapi.json http://localhost:5080/openapi/v1.json
head -c 300 openapi.json; echo
grep -oE '"/[a-z/{}]*": \{' openapi.json | sort -uCheck it worked
The document starts with "openapi": "3.1.1" and a title of TodoApi | v1. The path list shows "/": {, "/todos": { and "/todos/{id}": {, and no /debug/fail. Search the file for "404": the GET, PUT and DELETE operations on /todos/{id} list it, because their return types say they can answer NotFound. Open openapi.json in any OpenAPI viewer to browse it.
Step 7 · Test the API in memory with xUnit
Curl checks vanish when you close the terminal. WebApplicationFactory from Microsoft.AspNetCore.Mvc.Testing starts your real Program, with the same services and middleware, on an in-memory server, and hands you an HttpClient for it. No port is opened, so tests run in parallel and in CI.
Stop the app in the second terminal with Ctrl+C. Then create an xUnit project, point it at the API project and add the testing package:
cd ~/todo-api-demo
dotnet new xunit -o TodoApi.Tests
dotnet sln add TodoApi.Tests
dotnet add TodoApi.Tests reference TodoApi
dotnet add TodoApi.Tests package Microsoft.AspNetCore.Mvc.Testing --version 10.0.15
rm TodoApi.Tests/UnitTest1.cs
grep PackageReference TodoApi.Tests/TodoApi.Tests.csprojIn .NET 10 the web SDK generates a public partial class Program for the top-level statements in Program.cs, so the test project can name it without any extra code. IClassFixture shares one factory, and so one app, between the tests in the class:
cat > TodoApi.Tests/TodoApiTests.cs <<'CS'
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Testing;
public class TodoApiTests : IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public TodoApiTests(WebApplicationFactory<Program> factory) => _factory = factory;
[Fact]
public async Task Created_todo_can_be_read_back()
{
var client = _factory.CreateClient();
var post = await client.PostAsJsonAsync("/todos", new { title = "Top up data bundle" });
Assert.Equal(HttpStatusCode.Created, post.StatusCode);
var created = await post.Content.ReadFromJsonAsync<Todo>();
var todo = await client.GetFromJsonAsync<Todo>(post.Headers.Location);
Assert.Equal("Top up data bundle", todo!.Title);
Assert.Equal(created!.Id, todo.Id);
}
[Fact]
public async Task Empty_title_is_rejected_with_validation_details()
{
var client = _factory.CreateClient();
var response = await client.PostAsJsonAsync("/todos", new { title = "" });
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
var problem = await response.Content.ReadFromJsonAsync<ValidationProblemDetails>();
Assert.Contains("Title", problem!.Errors.Keys);
}
[Fact]
public async Task Missing_todo_returns_problem_details()
{
var client = _factory.CreateClient();
var response = await client.GetAsync("/todos/9999");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
}
[Fact]
public async Task OpenApi_document_lists_the_todo_routes()
{
var client = _factory.CreateClient();
var json = await client.GetStringAsync("/openapi/v1.json");
Assert.Contains("\"/todos/{id}\"", json);
}
}
CS
dotnet testThe factory runs the app in the Development environment by default, which is why the OpenAPI test can fetch /openapi/v1.json. To test with a different store, call _factory.WithWebHostBuilder(b => b.ConfigureServices(...)) and register your own ITodoStore; the endpoints never need to know.
Check it worked
dotnet test builds both projects and ends with a line like Passed! - Failed: 0, Passed: 4, Skipped: 0, Total: 4. To see a failure, change HttpStatusCode.NotFound to HttpStatusCode.Gone in the third test and run dotnet test again: that test fails with the expected and actual values. Change it back. The grep after dotnet new xunit printed the test packages the template chose and their versions; note them, because a later SDK can ship a template with newer xUnit packages and slightly different output.
Step 8 · Clean up
Make sure the app is stopped (Ctrl+C in the second terminal), then remove the project folder:
cd ~
rm -rf ~/todo-api-demoCheck it worked
ls ~/todo-api-demo reports No such file or directory, and curl http://localhost:5080/ fails to connect. The NuGet packages stay in ~/.nuget/packages as a cache for other projects; dotnet nuget locals all --clear removes them if you need the space.
Next steps
- Give an ASP.NET Core API a SQLite database with migrations: store data in an ASP.NET Core API with Entity Framework Core.
- Design error bodies that clients can act on: return API errors as Problem Details (RFC 9457).
- Script the requests you made here into a repeatable check: test an API with curl.
- Compare the same kind of API on the JVM: build a REST API with Spring Boot 4.
Related tutorials
- Hello World in C#: dotnet new, top-level statements and file-based appsYou will install the .NET 10 SDK, create and run a C# console app with dotnet new and dotnet run, run a single .cs file with no project, read a name safely from the keyboard and publish a self-contained executable.
- Store data in an ASP.NET Core API with Entity Framework CoreYou will give an ASP.NET Core minimal API a SQLite database through EF Core 10, with migrations, tracked and untracked queries, logged SQL, a version token that turns lost updates into 409 responses, and xUnit tests that each run against a fresh database.
- Return consistent API errors with Problem Details (RFC 9457)You will give every error from an Express 5 API the same application/problem+json shape, with a stable type URI per error kind, field errors, no stack traces, a client that handles them all in one place, an OpenAPI description and the same contract in FastAPI.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials