Skip to content

Add a feature ​

One page for every option

This page covers every choice of --Persistence, --Auth, --IncludeTests and --Aspire. A label says which options a part is for; the copy in your app's docs/ folder has only yours. ApiHost stands for your app's name.

A feature is a folder under src/ApiHost/Features/ with its endpoints, request records, validators, messages and handlers, often in one file each, plus a folder under src/Client/src/features/. Nothing needs registering: Wolverine finds endpoints by their attributes and handlers by name. This guide adds a small "Notes" feature; the Todo feature shows every pattern in more depth (see Architecture).

1. The API ​

Create src/ApiHost/Features/Notes/Notes.cs:

csharp
using Marten;
using System.Security.Claims;
using ApiHost.Identity;
using Microsoft.AspNetCore.Authorization;
using FluentValidation;
using Wolverine.Http;

namespace ApiHost.Features.Notes;

public class Note
{
    public Guid Id { get; set; }
    public string Text { get; set; } = string.Empty;
    public string OwnerId { get; set; } = string.Empty;
}

public record AddNote(string Text);

// Runs before the endpoint; an invalid request gets a 400 ProblemDetails response.
public class AddNoteValidator : AbstractValidator<AddNote>
{
    public AddNoteValidator() => RuleFor(x => x.Text).NotEmpty().MaximumLength(500);
}

public static class NoteEndpoints
{
    [Authorize]
    [WolverinePost("/api/notes")]
    public static Note Add(AddNote request, IDocumentSession session, ClaimsPrincipal user)
    {
        var note = new Note { Id = Guid.CreateVersion7(), Text = request.Text, OwnerId = user.GetUserId() };
        session.Store(note);   // saved after the endpoint runs, with any messages it returns
        return note;
    }

    [Authorize]
    [WolverineGet("/api/notes")]
    public static Task<IReadOnlyList<Note>> List(IQuerySession session, ClaimsPrincipal user)
    {
        var ownerId = user.GetUserId();
        return session.Query<Note>().Where(n => n.OwnerId == ownerId).ToListAsync();
    }
}
csharp
using Marten;
using FluentValidation;
using Wolverine.Http;

namespace ApiHost.Features.Notes;

public class Note
{
    public Guid Id { get; set; }
    public string Text { get; set; } = string.Empty;
}

public record AddNote(string Text);

// Runs before the endpoint; an invalid request gets a 400 ProblemDetails response.
public class AddNoteValidator : AbstractValidator<AddNote>
{
    public AddNoteValidator() => RuleFor(x => x.Text).NotEmpty().MaximumLength(500);
}

public static class NoteEndpoints
{
    [WolverinePost("/api/notes")]
    public static Note Add(AddNote request, IDocumentSession session)
    {
        var note = new Note { Id = Guid.CreateVersion7(), Text = request.Text };
        session.Store(note);   // saved after the endpoint runs, with any messages it returns
        return note;
    }

    [WolverineGet("/api/notes")]
    public static Task<IReadOnlyList<Note>> List(IQuerySession session)
        => session.Query<Note>().ToListAsync();
}
csharp
using ApiHost.Data.EfCore;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using ApiHost.Identity;
using Microsoft.AspNetCore.Authorization;
using FluentValidation;
using Wolverine.Http;

namespace ApiHost.Features.Notes;

public class Note
{
    public Guid Id { get; set; }
    public string Text { get; set; } = string.Empty;
    public string OwnerId { get; set; } = string.Empty;
}

public record AddNote(string Text);

// Runs before the endpoint; an invalid request gets a 400 ProblemDetails response.
public class AddNoteValidator : AbstractValidator<AddNote>
{
    public AddNoteValidator() => RuleFor(x => x.Text).NotEmpty().MaximumLength(500);
}

public static class NoteEndpoints
{
    [Authorize]
    [WolverinePost("/api/notes")]
    public static Note Add(AddNote request, AppDbContext db, ClaimsPrincipal user)
    {
        var note = new Note { Id = Guid.CreateVersion7(), Text = request.Text, OwnerId = user.GetUserId() };
        db.Notes.Add(note);    // saved after the endpoint runs, with any messages it returns
        return note;
    }

    [Authorize]
    [WolverineGet("/api/notes")]
    public static Task<List<Note>> List(AppDbContext db, ClaimsPrincipal user)
    {
        var ownerId = user.GetUserId();
        return db.Notes.Where(n => n.OwnerId == ownerId).ToListAsync();
    }
}
csharp
using ApiHost.Data.EfCore;
using Microsoft.EntityFrameworkCore;
using FluentValidation;
using Wolverine.Http;

namespace ApiHost.Features.Notes;

public class Note
{
    public Guid Id { get; set; }
    public string Text { get; set; } = string.Empty;
}

public record AddNote(string Text);

// Runs before the endpoint; an invalid request gets a 400 ProblemDetails response.
public class AddNoteValidator : AbstractValidator<AddNote>
{
    public AddNoteValidator() => RuleFor(x => x.Text).NotEmpty().MaximumLength(500);
}

public static class NoteEndpoints
{
    [WolverinePost("/api/notes")]
    public static Note Add(AddNote request, AppDbContext db)
    {
        var note = new Note { Id = Guid.CreateVersion7(), Text = request.Text };
        db.Notes.Add(note);    // saved after the endpoint runs, with any messages it returns
        return note;
    }

    [WolverineGet("/api/notes")]
    public static Task<List<Note>> List(AppDbContext db) => db.Notes.ToListAsync();
}

Marten

With accounts

Marten stores Note as a JSON document and creates its table when the app starts. Index the owner for fast per-user queries in Data/Marten/MartenPersistence.cs: opts.Schema.For<Note>().Index(n => n.OwnerId);

Without accounts

Marten stores Note as a JSON document and creates its table when the app starts.

EF Core

Add the table: in Data/EfCore/AppDbContext.cs add public DbSet<Note> Notes => Set<Note>(); (and, with an owner, an index on OwnerId in OnModelCreating), then add a migration.

Other things a feature often needs:

  • Background work: return a message from the endpoint and handle it in a class whose name ends in Handler, like TodoCompleted and TodoCompletedHandler. It's saved with your data (the outbox) and runs even after a restart.
  • Live updates: route a message to browsers with opts.PublishMessage<YourMessage>().ToSignalR(); in Program.cs, and listen for it in the client like features/todos/useTodoRealtime.ts.
  • With accounts Users' data: handle AccountDeleted and delete the user's notes, like Features/Todos/DeleteTodosOfDeletedAccountHandler.cs.
  • With accounts Security: answer 404, not 403, when someone asks for another user's record, so its existence isn't revealed.

2. The client ​

With accounts

  1. Run the API and update the client's types: npm run gen:api in src/Client.
  2. Create src/Client/src/features/notes/ with TanStack Query hooks (copy features/todos/todoQueries.ts) and a page component.
  3. Add a route module, src/Client/src/routes/notes.tsx, like routes/todos.tsx: it default-exports the page and gives its title in handle (with index: true only if search engines should list it, which also pre-renders it). Add it to src/Client/src/routes.ts (route('notes', 'routes/notes.tsx')), add its path to src/Client/src/pages.ts (a unit test fails until they match), and add a NavItem for it in App.tsx. Put the route inside the routes/require-auth.tsx layout if it needs a login, and add the NavItem in features/account/AccountNavigation.tsx.

Without accounts

  1. Run the API and update the client's types: npm run gen:api in src/Client.
  2. Create src/Client/src/features/notes/ with TanStack Query hooks (copy features/todos/todoQueries.ts) and a page component.
  3. Add a route module, src/Client/src/routes/notes.tsx, like routes/todos.tsx: it default-exports the page and gives its title in handle (with index: true only if search engines should list it, which also pre-renders it). Add it to src/Client/src/routes.ts (route('notes', 'routes/notes.tsx')), add its path to src/Client/src/pages.ts (a unit test fails until they match), and add a NavItem for it in App.tsx.

3. Tests ​

  • With the tests An API test in tests/ApiHost.Tests (copy TodoEndpointsTests.cs): adding, listing and validation.
  • With the tests With accounts That one user can't see another's notes (copy TodoAuthorizationTests.cs).
  • A client test next to the page (NotesPage.test.tsx; copy features/todos/TodoList.test.tsx).

See Testing.

Documentation for v0.8.0. Released under the MIT licence.