TExcelTAD
Home › ASP.NET Core › ASP.NET Core Mini Project

ASP.NET Core Mini Project: Notes API

In this project you will build NotesApi, a small REST API for notes with tags, from an empty template to a tested, database-backed service. It pulls together most of this course: minimal APIs, route groups, dependency injection, validation, typed results, Entity Framework Core and integration testing.

The finished API:

Method Route Result
GET /notes?tag=work 200 with all notes, optionally filtered by tag
GET /notes/{id} 200 with the note, or 404
POST /notes 201 with a Location header, or 400 with validation errors
PUT /notes/{id} 204, 400 or 404
DELETE /notes/{id} 204 or 404

Note: ASP.NET Core cannot run inside this page, so the server code is shown in normal code blocks and the HTTP calls are simulated terminal sessions. The core logic — the store, the tag filter and the validation — is repeated in plain C# playgrounds that really run.

Step 1: Create the project

bash · try it yourself
$ dotnet new web -o NotesApi
$ cd NotesApi
$ dotnet run --urls http://localhost:5000
The template "ASP.NET Core Empty" was created successfully.

Processing post-creation actions...
Restoring /home/dev/NotesApi/NotesApi.csproj:
Restore succeeded.

info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /home/dev/NotesApi

The template's Program.cs maps a single Hello World! endpoint. We will replace it piece by piece.

Step 2: The model and an in-memory store

A note is an immutable record; changes produce a new instance with with. The store hides how notes are kept, so we can swap it for a database later without touching the endpoints. Put this in Notes.cs:

csharp
public record Note(int Id, string Title, string Body, string[] Tags);

public record NoteInput(string Title, string Body, string[]? Tags);

public interface INoteStore
{
    IReadOnlyList<Note> List(string? tag);
    Note? Find(int id);
    Note Add(NoteInput input);
    bool Update(int id, NoteInput input);
    bool Delete(int id);
}

public class InMemoryNoteStore : INoteStore
{
    private readonly Dictionary<int, Note> _notes = new();
    private readonly Lock _gate = new();
    private int _nextId = 1;

    public IReadOnlyList<Note> List(string? tag)
    {
        lock (_gate)
            return _notes.Values
                .Where(n => tag is null || n.Tags.Contains(tag, StringComparer.OrdinalIgnoreCase))
                .OrderBy(n => n.Id)
                .ToList();
    }

    public Note? Find(int id) { lock (_gate) return _notes.GetValueOrDefault(id); }

    public Note Add(NoteInput input)
    {
        lock (_gate)
        {
            var note = new Note(_nextId++, input.Title, input.Body, input.Tags ?? []);
            _notes[note.Id] = note;
            return note;
        }
    }

    public bool Update(int id, NoteInput input)
    {
        lock (_gate)
        {
            if (!_notes.TryGetValue(id, out var old)) return false;
            _notes[id] = old with { Title = input.Title, Body = input.Body, Tags = input.Tags ?? [] };
            return true;
        }
    }

    public bool Delete(int id) { lock (_gate) return _notes.Remove(id); }
}

Kestrel serves requests on many threads at once, and a store registered as a singleton is shared by all of them — hence the lock (System.Threading.Lock is new in .NET 9). Here is the same store logic running for real, without the web server:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var store = new NoteStore();
store.Add(new NoteInput("Buy milk", "2 litres", new[] { "home" }));
store.Add(new NoteInput("Sprint review", "Friday 10:00", new[] { "work", "meeting" }));
store.Add(new NoteInput("Fix login bug", "Ticket #812", new[] { "Work" }));

Console.WriteLine("All:  " + string.Join(", ", store.List(null).Select(n => n.Title)));
Console.WriteLine("work: " + string.Join(", ", store.List("work").Select(n => n.Title)));

Console.WriteLine(
quot;Update 1: {store.Update(1, new NoteInput("Buy oat milk", "2 litres", new[] { "home" }))}"); Console.WriteLine(
quot;Update 9: {store.Update(9, new NoteInput("x", "y", null))}"); Console.WriteLine(
quot;Note 1 is now: {store.Find(1)?.Title}"); Console.WriteLine(
quot;Delete 2: {store.Delete(2)}, again: {store.Delete(2)}"); Console.WriteLine(
quot;Remaining ids: {string.Join(", ", store.List(null).Select(n => n.Id))}"); record Note(int Id, string Title, string Body, string[] Tags); record NoteInput(string Title, string Body, string[] Tags); class NoteStore { private readonly Dictionary<int, Note> notes = new(); private int nextId = 1; public List<Note> List(string tag) => notes.Values .Where(n => tag is null || n.Tags.Contains(tag, StringComparer.OrdinalIgnoreCase)) .OrderBy(n => n.Id) .ToList(); public Note Find(int id) => notes.GetValueOrDefault(id); public Note Add(NoteInput input) { var note = new Note(nextId++, input.Title, input.Body, input.Tags ?? Array.Empty<string>()); notes[note.Id] = note; return note; } public bool Update(int id, NoteInput input) { if (!notes.TryGetValue(id, out var old)) return false; notes[id] = old with { Title = input.Title, Body = input.Body, Tags = input.Tags ?? Array.Empty<string>() }; return true; } public bool Delete(int id) => notes.Remove(id); }
All:  Buy milk, Sprint review, Fix login bug
work: Sprint review, Fix login bug
Update 1: True
Update 9: False
Note 1 is now: Buy oat milk
Delete 2: True, again: False
Remaining ids: 1, 3

Notice the case-insensitive tag match: ?tag=work also finds the note tagged Work.

Step 3: Validation

Clients send any JSON they like, so we check it before storing it. A small static validator returns a dictionary of field → messages, which is exactly the shape TypedResults.ValidationProblem expects:

csharp
public static class NoteValidator
{
    public static Dictionary<string, string[]> Validate(NoteInput input)
    {
        var errors = new Dictionary<string, string[]>();
        if (string.IsNullOrWhiteSpace(input.Title))
            errors["title"] = ["Title is required."];
        else if (input.Title.Length > 100)
            errors["title"] = ["Title must be at most 100 characters."];
        if (input.Tags is { Length: > 5 })
            errors["tags"] = ["A note can have at most 5 tags."];
        return errors;
    }
}

Try it on a few inputs:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;

var inputs = new[]
{
    new NoteInput("Groceries", "eggs, bread", new[] { "home" }),
    new NoteInput("  ", "no title", null),
    new NoteInput(new string('x', 120), "", new[] { "a", "b", "c", "d", "e", "f" }),
};

foreach (var input in inputs)
{
    var errors = NoteValidator.Validate(input);
    Console.WriteLine(errors.Count == 0 ? "valid" : JsonSerializer.Serialize(errors));
}

record NoteInput(string Title, string Body, string[] Tags);

static class NoteValidator
{
    public static Dictionary<string, string[]> Validate(NoteInput input)
    {
        var errors = new Dictionary<string, string[]>();
        if (string.IsNullOrWhiteSpace(input.Title))
            errors["title"] = new[] { "Title is required." };
        else if (input.Title.Length > 100)
            errors["title"] = new[] { "Title must be at most 100 characters." };
        if (input.Tags is { Length: > 5 })
            errors["tags"] = new[] { "A note can have at most 5 tags." };
        return errors;
    }
}
valid
{"title":["Title is required."]}
{"title":["Title must be at most 100 characters."],"tags":["A note can have at most 5 tags."]}

Step 4: The endpoints

Now wire everything up in Program.cs. The store is registered as a singleton, the endpoints share the /notes prefix through MapGroup, and each handler declares its possible results with Results<...> and TypedResults, so they are type-checked and documented in OpenAPI.

csharp
using Microsoft.AspNetCore.Http.HttpResults;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<INoteStore, InMemoryNoteStore>();

var app = builder.Build();
var notes = app.MapGroup("/notes");

notes.MapGet("/", (string? tag, INoteStore store) => TypedResults.Ok(store.List(tag)));

notes.MapGet("/{id:int}", Results<Ok<Note>, NotFound> (int id, INoteStore store) =>
    store.Find(id) is { } note ? TypedResults.Ok(note) : TypedResults.NotFound());

notes.MapPost("/", Results<Created<Note>, ValidationProblem> (NoteInput input, INoteStore store) =>
{
    var errors = NoteValidator.Validate(input);
    if (errors.Count > 0) return TypedResults.ValidationProblem(errors);

    var note = store.Add(input);
    return TypedResults.Created(
quot;/notes/{note.Id}", note); }); notes.MapPut("/{id:int}", Results<NoContent, NotFound, ValidationProblem> (int id, NoteInput input, INoteStore store) => { var errors = NoteValidator.Validate(input); if (errors.Count > 0) return TypedResults.ValidationProblem(errors); return store.Update(id, input) ? TypedResults.NoContent() : TypedResults.NotFound(); }); notes.MapDelete("/{id:int}", Results<NoContent, NotFound> (int id, INoteStore store) => store.Delete(id) ? TypedResults.NoContent() : TypedResults.NotFound()); app.Run(); public partial class Program { } // lets the test project reference the app (step 6)

Restart the app and exercise it from a second terminal:

bash · try it yourself
$ curl -i -X POST localhost:5000/notes -H "Content-Type: application/json" -d '{"title":"Sprint review","body":"Friday 10:00","tags":["work"]}'
$ curl -s -X POST localhost:5000/notes -H "Content-Type: application/json" -d '{"title":"Buy milk","body":"2 litres","tags":["home"]}'
$ curl -s "localhost:5000/notes?tag=work"
$ curl -i localhost:5000/notes/42
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Location: /notes/1
Transfer-Encoding: chunked

{"id":1,"title":"Sprint review","body":"Friday 10:00","tags":["work"]}{"id":2,"title":"Buy milk","body":"2 litres","tags":["home"]}[{"id":1,"title":"Sprint review","body":"Friday 10:00","tags":["work"]}]HTTP/1.1 404 Not Found
Content-Length: 0
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel

curl -s does not print a trailing newline, which is why the JSON bodies run together. Now the error paths and the remaining verbs:

bash · try it yourself
$ curl -s -X POST localhost:5000/notes -H "Content-Type: application/json" -d '{"title":"","body":"oops"}'
$ curl -s -o /dev/null -w "%{http_code}\n" -X PUT localhost:5000/notes/2 -H "Content-Type: application/json" -d '{"title":"Buy oat milk","body":"2 litres","tags":["home"]}'
$ curl -s -o /dev/null -w "%{http_code}\n" -X DELETE localhost:5000/notes/1
$ curl -s -o /dev/null -w "%{http_code}\n" -X DELETE localhost:5000/notes/1
$ curl -s localhost:5000/notes
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred.","status":400,"errors":{"title":["Title is required."]}}204
204
404
[{"id":2,"title":"Buy oat milk","body":"2 litres","tags":["home"]}]

Tip: Deleting the same note twice returns 204 and then 404. Clients can rely on this to tell "already gone" from "done".

Step 5: Swap in EF Core and SQLite

The in-memory store forgets everything on restart. Add EF Core with SQLite:

bash · try it yourself
$ dotnet add package Microsoft.EntityFrameworkCore.Sqlite --version 9.0.10
$ dotnet add package Microsoft.EntityFrameworkCore.Design --version 9.0.10
$ dotnet tool install --global dotnet-ef --version 9.0.10
info : Adding PackageReference for package 'Microsoft.EntityFrameworkCore.Sqlite' into project '/home/dev/NotesApi/NotesApi.csproj'.
info : PackageReference for package 'Microsoft.EntityFrameworkCore.Sqlite' version '9.0.10' added to file '/home/dev/NotesApi/NotesApi.csproj'.
info : Adding PackageReference for package 'Microsoft.EntityFrameworkCore.Design' into project '/home/dev/NotesApi/NotesApi.csproj'.
info : PackageReference for package 'Microsoft.EntityFrameworkCore.Design' version '9.0.10' added to file '/home/dev/NotesApi/NotesApi.csproj'.
You can invoke the tool using the following command: dotnet-ef
Tool 'dotnet-ef' (version '9.0.10') was successfully installed.

Create a DbContext and a second implementation of INoteStore. EF Core stores the string[] tags as a JSON column in SQLite automatically (primitive collections, since EF Core 8). Because a DbContext is scoped, the store that uses it must be scoped too:

csharp
using Microsoft.EntityFrameworkCore;

public class NotesDb(DbContextOptions<NotesDb> options) : DbContext(options)
{
    public DbSet<Note> Notes => Set<Note>();
}

public class EfNoteStore(NotesDb db) : INoteStore
{
    public IReadOnlyList<Note> List(string? tag) =>
        db.Notes.AsNoTracking()
          .Where(n => tag == null || n.Tags.Contains(tag))
          .OrderBy(n => n.Id)
          .ToList();

    public Note? Find(int id) => db.Notes.AsNoTracking().FirstOrDefault(n => n.Id == id);

    public Note Add(NoteInput input)
    {
        var note = new Note(0, input.Title, input.Body, input.Tags ?? []);
        db.Notes.Add(note);
        db.SaveChanges();                 // the database generates the Id
        return note;
    }

    public bool Update(int id, NoteInput input)
    {
        var existing = db.Notes.Find(id);
        if (existing is null) return false;
        db.Entry(existing).CurrentValues.SetValues(
            existing with { Title = input.Title, Body = input.Body, Tags = input.Tags ?? [] });
        db.SaveChanges();
        return true;
    }

    public bool Delete(int id) => db.Notes.Where(n => n.Id == id).ExecuteDelete() == 1;
}

In Program.cs, only the registrations change — the endpoints stay exactly as they are:

csharp
builder.Services.AddDbContext<NotesDb>(o =>
    o.UseSqlite(builder.Configuration.GetConnectionString("Notes") ?? "Data Source=notes.db"));
builder.Services.AddScoped<INoteStore, EfNoteStore>();

Note: The SQLite tag filter compares exactly, so it is case-sensitive, unlike the in-memory version. Normalising tags to lowercase in the validator is a simple fix. In a real app you would also switch the store to async methods (ToListAsync, SaveChangesAsync).

Create the database with a migration and run again:

bash · try it yourself
$ dotnet ef migrations add InitialCreate
$ dotnet ef database update
Build started...
Build succeeded.
Done. To undo this action, use 'ef migrations remove'
Build started...
Build succeeded.
Applying migration '20261016090000_InitialCreate'.
Done.

Notes now survive a restart.

Step 6: An integration test

WebApplicationFactory<Program> starts the whole app in memory, with a real pipeline but no network port. Create an xUnit project next to the API:

bash · try it yourself
$ dotnet new xunit -o NotesApi.Tests
$ dotnet add NotesApi.Tests reference NotesApi
$ dotnet add NotesApi.Tests package Microsoft.AspNetCore.Mvc.Testing --version 9.0.10
The template "xUnit Test Project" was created successfully.

Processing post-creation actions...
Restoring /home/dev/NotesApi.Tests/NotesApi.Tests.csproj:
Restore succeeded.

Reference `../NotesApi/NotesApi.csproj` added to the project.
info : PackageReference for package 'Microsoft.AspNetCore.Mvc.Testing' version '9.0.10' added to file '/home/dev/NotesApi.Tests/NotesApi.Tests.csproj'.

The test swaps the EF store back to the in-memory one, so it needs no database file:

csharp
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;

public class NotesApiTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    private HttpClient CreateClient() =>
        factory.WithWebHostBuilder(b => b.ConfigureServices(services =>
            services.AddSingleton<INoteStore, InMemoryNoteStore>()))   // last registration wins
        .CreateClient();

    [Fact]
    public async Task Post_then_get_returns_the_note()
    {
        var client = CreateClient();

        var post = await client.PostAsJsonAsync("/notes", new NoteInput("Test", "Body", ["qa"]));
        Assert.Equal(HttpStatusCode.Created, post.StatusCode);

        var note = await client.GetFromJsonAsync<Note>(post.Headers.Location);
        Assert.Equal("Test", note!.Title);
    }

    [Fact]
    public async Task Post_without_title_returns_400()
    {
        var response = await CreateClient().PostAsJsonAsync("/notes", new NoteInput("", "x", null));
        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
    }
}
bash · try it yourself
$ dotnet test NotesApi.Tests
Restore complete (0.8s)
  NotesApi succeeded (2.1s) → NotesApi/bin/Debug/net9.0/NotesApi.dll
  NotesApi.Tests succeeded (1.4s) → NotesApi.Tests/bin/Debug/net9.0/NotesApi.Tests.dll
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 9.0.10)
[xUnit.net 00:00:00.12]   Discovering: NotesApi.Tests
[xUnit.net 00:00:00.16]   Discovered:  NotesApi.Tests
[xUnit.net 00:00:00.17]   Starting:    NotesApi.Tests
[xUnit.net 00:00:01.02]   Finished:    NotesApi.Tests
  NotesApi.Tests test succeeded (2.3s)

Test summary: total: 2, failed: 0, succeeded: 2, skipped: 0, duration: 2.3s
Build succeeded in 6.9s

Ideas for extending the project

  • Add paging (?page=2&size=20) and return the total count in an X-Total-Count header.
  • Protect PUT and DELETE with .RequireAuthorization() and JWT bearer authentication.
  • Add app.MapHealthChecks("/healthz") with an EF Core database check.
  • Generate an OpenAPI document with builder.Services.AddOpenApi() and app.MapOpenApi().
  • Package it in a container with dotnet publish /t:PublishContainer.

Test yourself

Why is EfNoteStore registered with AddScoped instead of AddSingleton?

  1. Scoped services are faster
  2. It depends on NotesDb, a scoped DbContext, and a singleton must not capture a scoped service
  3. SQLite only allows one connection per app
  4. Minimal APIs cannot inject singletons

What does the POST endpoint return when the title is empty?

  1. 201 with an empty note
  2. 404 Not Found
  3. 500 Internal Server Error
  4. 400 with a ValidationProblem body listing the title error

Why does Program.cs end with public partial class Program { }?

  1. So the test project can use WebApplicationFactory<Program>
  2. It is required by MapGroup
  3. It enables top-level statements
  4. It registers Program in dependency injection