Lesson 23 of 24

In progress

Course progress

C# and .NET

A minimal ASP.NET Core API

Turn a service into HTTP endpoints with minimal APIs, return proper status codes, and validate input at the boundary.

ASP.NET Core hosts your code as an HTTP service. Minimal APIs skip the controller ceremony: a route, a method and a delegate are enough for a small service.

What you will learn

  • Create a minimal API project and map routes.
  • Return the right status code for each outcome.
  • Bind and validate a request body.

Create the project

dotnet new web -o TasksApi
cd TasksApi
dotnet run

dotnet new web produces a Program.cs with a minimal host. dotnet run starts Kestrel on a port printed to the console.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Tasks API");
app.Run();

MapGet associates a route with a delegate. The delegate’s return value becomes the response body, and the framework writes it as text when it is a string.

Routes and handlers

var tasks = new List<TaskItem>();
app.MapGet("/tasks", () => tasks);
app.MapGet("/tasks/{id:int}", (int id) =>
tasks.FirstOrDefault(t => t.Id == id) is { } task
? Results.Ok(task)
: Results.NotFound());
app.MapPost("/tasks", (TaskItem input) =>
{
var created = input with { Id = tasks.Count + 1 };
tasks.Add(created);
return Results.Created($"/tasks/{created.Id}", created);
});

The {id:int} constraint makes a non-numeric id a 404 rather than an exception. The parameter is bound from the route, and a complex parameter is bound from the JSON body.

Results.Ok, NotFound and Created return the right status code with the body. Returning a bare object defaults to 200, which is wrong for a creation.

Status codes that mean something

  • 200 for a successful read.
  • 201 for a creation, with a Location header.
  • 204 for a successful delete with no body.
  • 400 for invalid input.
  • 404 for a missing resource.
  • 409 for a conflict such as a duplicate.
  • 500 for an unexpected failure, which the framework handles if you let the exception escape.

Getting these right is most of what makes an API pleasant to consume. A creation that returns 200 forces every client to guess.

Validation

app.MapPost("/tasks", (TaskItem input) =>
{
if (string.IsNullOrWhiteSpace(input.Title))
return Results.ValidationProblem(new Dictionary<string, string[]>
{
["title"] = new[] { "Title is required." }
});
var created = input with { Id = tasks.Count + 1 };
tasks.Add(created);
return Results.Created($"/tasks/{created.Id}", created);
});

Results.ValidationProblem returns 400 with a problem-details body, which is the standard shape for validation errors. Modern .NET also supports data annotations on the record, which the framework validates before the handler runs.

Validate at the boundary: the handler checks the shape of the request, and the service checks the rules that apply regardless of how it was called.

Dependency injection

builder.Services.AddSingleton<ITaskStore, JsonTaskStore>();
builder.Services.AddScoped<TaskService>();
app.MapGet("/tasks", (TaskService service) => service.List(onlyOpen: true));

The container creates the objects and supplies them to handlers. Singleton is one instance for the process, Scoped one per request, Transient a new one every time.

A scoped service per request is the right default for anything holding state about the current request. A singleton must be thread-safe, because requests run concurrently.

Configuration

string path = builder.Configuration["Data:Path"] ?? "data/tasks.json";

appsettings.json and environment variables feed the configuration, with environment variables taking precedence. Secrets belong in user secrets during development and in the host’s secret store in production, never in the repository.

A complete Program.cs

using Tasks.Api;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<ITaskStore>(_ =>
new JsonTaskStore(builder.Configuration["Data:Path"] ?? "data/tasks.json"));
builder.Services.AddSingleton<TaskService>();
var app = builder.Build();
app.MapGet("/tasks", (TaskService s) => Results.Ok(s.List(onlyOpen: false)));
app.MapPost("/tasks", (TaskInput input, TaskService s) =>
{
if (string.IsNullOrWhiteSpace(input.Title))
return Results.BadRequest(new { error = "title required" });
var created = s.Add(input.Title, input.Priority);
return Results.Created($"/tasks/{created.Id}", created);
});
app.Run();

The handlers are two lines each, because the rules live in the service. That is the same separation as the console app, which is the point: the interface changed, the logic did not.

What minimal APIs leave out

There is no filter pipeline and no per-controller model-binding configuration. For a dozen endpoints that is a benefit; for a large service, Program.cs grows into a long file. Grouping endpoints into extension methods — app.MapTaskEndpoints() — keeps each file small and the wiring readable.

OpenAPI documentation is opt-in: add the package, call AddOpenApi() and MapOpenApi(), and the endpoint descriptions follow from the route and the types. That is worth doing early, because it turns the API into something another team can explore without reading the code.

Testing the endpoints

dotnet run
curl -X POST http://localhost:5000/tasks 
-H "Content-Type: application/json" 
-d '{"title":"Write docs","priority":"Normal"}'

WebApplicationFactory in Microsoft.AspNetCore.Mvc.Testing starts the app in memory for integration tests, which is faster and more reliable than hitting a real port.

Returning a raw object from a POST handler. It defaults to 200 and omits the Location header, so clients cannot discover the new resource’s URL. Use Results.Created.

Add a DELETE /tasks/{id} endpoint that returns 204 when it removed something and 404 when the id is unknown.

Show solution
app.MapDelete("/tasks/{id:int}", (int id, TaskService service) => service.Remove(id) ? Results.NoContent() : Results.NotFound());

The service returns a bool for "found and removed", and the handler maps it to a status code. Results.NoContent() produces a 204 with no body, which is the correct response for a successful delete.

Recap

  • Minimal APIs map a route and method to a delegate; return typed results for correct status codes.
  • Validate at the boundary, and keep business rules in the service.
  • Register dependencies by lifetime: singleton for shared, scoped per request.

Next, the capstone: test the service, then ship the console app and the API together.

Minimal APIs or controllers?
Minimal APIs for small services and endpoints; controllers for larger teams that want the conventions. Both run on the same pipeline.
Where do secrets go?
User secrets in development, the host’s environment or secret manager in production, never in `appsettings.json` committed to git.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.