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:
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();
}
}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();
}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();
}
}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, likeTodoCompletedandTodoCompletedHandler. 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();inProgram.cs, and listen for it in the client likefeatures/todos/useTodoRealtime.ts. - With accounts Users' data: handle
AccountDeletedand delete the user's notes, likeFeatures/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
- Run the API and update the client's types:
npm run gen:apiinsrc/Client. - Create
src/Client/src/features/notes/with TanStack Query hooks (copyfeatures/todos/todoQueries.ts) and a page component. - Add a route module,
src/Client/src/routes/notes.tsx, likeroutes/todos.tsx: it default-exports the page and gives its title inhandle(withindex: trueonly if search engines should list it, which also pre-renders it). Add it tosrc/Client/src/routes.ts(route('notes', 'routes/notes.tsx')), add its path tosrc/Client/src/pages.ts(a unit test fails until they match), and add aNavItemfor it inApp.tsx. Put the route inside theroutes/require-auth.tsxlayout if it needs a login, and add theNavIteminfeatures/account/AccountNavigation.tsx.
Without accounts
- Run the API and update the client's types:
npm run gen:apiinsrc/Client. - Create
src/Client/src/features/notes/with TanStack Query hooks (copyfeatures/todos/todoQueries.ts) and a page component. - Add a route module,
src/Client/src/routes/notes.tsx, likeroutes/todos.tsx: it default-exports the page and gives its title inhandle(withindex: trueonly if search engines should list it, which also pre-renders it). Add it tosrc/Client/src/routes.ts(route('notes', 'routes/notes.tsx')), add its path tosrc/Client/src/pages.ts(a unit test fails until they match), and add aNavItemfor it inApp.tsx.
3. Tests
- With the tests An API test in
tests/ApiHost.Tests(copyTodoEndpointsTests.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; copyfeatures/todos/TodoList.test.tsx).
See Testing.