Extrode.NativeWeb.Scaffold
0.1.0
See the version list below for details.
dotnet add package Extrode.NativeWeb.Scaffold --version 0.1.0
NuGet\Install-Package Extrode.NativeWeb.Scaffold -Version 0.1.0
<PackageReference Include="Extrode.NativeWeb.Scaffold" Version="0.1.0" />
<PackageVersion Include="Extrode.NativeWeb.Scaffold" Version="0.1.0" />
<PackageReference Include="Extrode.NativeWeb.Scaffold" />
paket add Extrode.NativeWeb.Scaffold --version 0.1.0
#r "nuget: Extrode.NativeWeb.Scaffold, 0.1.0"
#:package Extrode.NativeWeb.Scaffold@0.1.0
#addin nuget:?package=Extrode.NativeWeb.Scaffold&version=0.1.0
#tool nuget:?package=Extrode.NativeWeb.Scaffold&version=0.1.0
nativeweb.scaffold
Declarative CRUD scaffolding for NativeWeb. Decorate a model; get an admin UI.
This project is the runtime half: the attributes, the IScaffoldStore<T> seam, and the
form-value converters the generated code calls. The build-time half is
libs/nativeweb.scaffold.generator. A consumer references both:
<ProjectReference Include="..\..\libs\nativeweb.scaffold\nativeweb.scaffold.csproj" />
<ProjectReference Include="..\..\libs\nativeweb.scaffold.generator\nativeweb.scaffold.generator.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
The whole API
[Scaffold(Display = "Articles", Route = "articles")]
[Auth(Role = "admin", Delete = "owner")]
public sealed class Article
{
[ScaffoldKey] public string Id { get; set; } = "";
[ScaffoldList][ScaffoldSearch]
[ScaffoldSort] public string Title { get; set; } = "";
[ScaffoldMultiline] public string Body { get; set; } = "";
[ScaffoldList] public ArticleStatus Status { get; set; }
[ScaffoldList] public DateOnly? PublishedAt { get; set; }
[ScaffoldList]
[ScaffoldReference(typeof(Category))] public string? CategoryKey { get; set; }
[ScaffoldRelation(typeof(Tag))] public IReadOnlyList<string> Tags { get; set; } = [];
[ScaffoldList][ScaffoldReadOnly]
[ScaffoldSort] public DateTime CreatedAt { get; set; }
}
| Attribute | On | Effect |
|---|---|---|
[Scaffold] |
class | Emits the routes. Display names the UI, Route the path segment |
[Auth] |
class | Role per operation; omitted means open |
[ScaffoldKey] |
property | The identity in every URL, and the tiebreaker in every order |
[ScaffoldList] |
property | A column. Label overrides the heading |
[ScaffoldSearch] |
property | Free-text search reaches it. No operators, no query language |
[ScaffoldSort] |
property | The list may be ordered by it, and its heading becomes a link |
[ScaffoldMultiline] |
property | <textarea> rather than <input> |
[ScaffoldReadOnly] |
property | Shown, never editable, no form input emitted |
[ScaffoldReference(typeof(T))] |
string? property |
Holds one key of another scaffolded model; a <select> of its rows, (none) first |
[ScaffoldRelation(typeof(T))] |
IReadOnlyList<string> property |
Holds zero or more keys of another scaffolded model; a checkbox list, or Control = ScaffoldRelationControl.MultiSelect |
The property type picks the input where no attribute does: string is an <input>, bool a
checkbox, a number type="number", a DateTime datetime-local, a DateOnly type="date", an
enum a <select> of its members. A nullable value type posts blank for null.
Implement IScaffoldStore<Article> (six methods, no query language — JauntyQ owns data access),
register it, and call app.MapScaffolding(). That is the entire wiring. See apps/sample.
Routes emitted per model, under /admin/{route}:
| Method | Path | Operation | Role from |
|---|---|---|---|
| GET | / |
list, search, sort, page | Read → Role |
| GET | /new |
create form | Write → Role |
| POST | / |
create | Write → Role |
| GET | /{id} |
edit form | Write → Role |
| POST | /{id} |
update | Write → Role |
| POST | /{id}/delete |
delete | Delete → Role |
No [Auth] at all means the routes are open. That is a choice made by omission.
Moving the UI off /admin
One assembly-level attribute, and every route, link, form action and redirect follows:
[assembly: ScaffoldRoot("/manage")]
/admin is only the default. "/" is legal and puts the scaffolding at the site root; a trailing
slash is trimmed; anything that is not a path — no leading /, or carrying a query, fragment or
space — is NWS002, a build error, and nothing is emitted. A typo cannot quietly publish an
admin UI at a path nobody chose.
Compile-time rather than a MapScaffolding(prefix) argument, deliberately: it keeps each model's
base path a const so every emitted URL is a literal. A runtime prefix would have to be threaded
through every generated method or parked in static state, and static state is shared by two hosts
in one process — which is exactly what an integration suite is.
The role in [Auth(Role = "admin")] is unrelated and has always been yours: any role name, with
Read/Write/Delete overriding it per operation.
Choosing a control for a relation
Four field kinds reach past a single column, and each is declared by the property's type or by one
attribute. apps/sample's Article carries all four so they can be compared side by side.
| Kind | Declared by | Renders as | Posts |
|---|---|---|---|
| Enum | an enum property |
<select> of the members, spaced (Published) |
the member name; anything else is refused |
| Date-only | a DateOnly or DateOnly? property |
<input type="date"> |
yyyy-MM-dd; blank is null when nullable |
| Reference | [ScaffoldReference(typeof(T))] on a string? |
<select> of T's rows, (none) first |
one key, or blank for null |
| Relation | [ScaffoldRelation(typeof(T))] on an IReadOnlyList<string> |
a checkbox list, or a <select multiple> |
one value per tick; nothing ticked posts nothing, which saves as no links |
A reference or relation target must itself be [Scaffold]ed, in the same assembly, keyed by a
string, and have its IScaffoldStore<T> registered: the form's choices come from that store, and a
listed reference column shows the target's label rather than the key. Both reads go to the target's
store directly, under the referrer's own [Auth], so a target scaffolded under a stricter role
still lends its labels to anyone who may read the referrer. The generator offers at most
OptionLimit (500) rows as choices, and reads the same 500 to label a list page; a held key past
that limit is still rendered, so saving a form never silently drops a link the admin could not see.
The relation control is a rendering choice and nothing else. Both post the same field, both bind to the same list, both save the whole ticked set; switch between them by editing one attribute and the store never notices:
[ScaffoldRelation(typeof(Tag))] // checkboxes
[ScaffoldRelation(typeof(Article), Control = ScaffoldRelationControl.MultiSelect)] // <select multiple>
| Pick | When |
|---|---|
| Checkboxes (the default) | The choices are few and stable and the admin wants to see them all at once: tags, roles, a handful of categories. Every choice is visible and ticked state is obvious. |
MultiSelect |
The choices are many or grow without bound: articles, users, orders. The control stays one box tall, is keyboard-searchable, and does not push the rest of the form off the screen. |
Whether a posted key exists is the store's call. A store refuses an unknown one with
ScaffoldRefusedException ("Tags has a choice that does not exist."), the same way it refuses
anything else only it can know; a check against the loaded choices would only be a snapshot.
Why a generator rather than reflection
NativeAOT bans the reflection every other ecosystem's scaffolding is built on: no
Activator.CreateInstance, no PropertyInfo.SetValue, no runtime model discovery. Measured in
docs/brainstorms/001-framework-direction.md §12, the platform's own declarative form binding is
closed too — a complex-type [FromForm] parameter emits RDG003, falls back to reflection, and
fails the build under TreatWarningsAsErrors; [AsParameters] compiles and then silently binds
every form field to null.
What does work is a type that binds itself through a compile-time static call:
IBindableFromHttpContext<TSelf>. That is what the generator emits, and everything below follows
from it.
And one thing a generator has to know that a hand-written endpoint does not. Measured
2026-08-19: the first NativeAOT publish of apps/sample failed with IL2026 and IL3050 on every
emitted MapGet/MapPost. The Request Delegate Generator only rewrites Map* calls it can see in
the compilation's own syntax trees, and Roslyn does not feed one generator's output to another — so
an emitted Map* call always binds the reflection-based Map*(..., Delegate) overload. The fix is
to emit RequestDelegates instead (ScaffoldEndpoints.Handle), which carry neither attribute
because there is nothing left to bind. Verified: dotnet publish -c Release -r win-x64 produces a
17 MB self-contained binary with zero trim or AOT warnings. This applies to any NativeWeb
generator that emits endpoints, not just this one.
Three guarantees the generated code carries
Mass assignment is closed by construction. The emitted form is a record whose constructor
parameters are exactly the editable properties. A key or a [ScaffoldReadOnly] property is not a
parameter, so no request can reach it — there is no allowlist to keep in sync, because the only
way to bind a field is to declare it. Read-only values are carried from the existing row instead.
Every mutating route re-attaches antiforgery metadata. [FromForm] is what normally attaches
IAntiforgeryMetadata, so a BindAsync-bound handler has none and UseAntiforgery() skips the
route entirely — a tokenless POST measured at 200 OK. RequiresAntiforgery.Instance is emitted on
all three POSTs; the guard cannot be forgotten because nobody writes it.
The content-type check lives inside BindAsync. Argument binding runs before the
endpoint-filter pipeline, so no endpoint filter can protect a bind. The generated BindAsync
calls FormBinding.RequireFormContentType itself, which raises BadHttpRequestException(415).
Sorting and paging, and the two things the store owes
The list orders by ?sort= and ?dir=, and pages by an opaque ?after= cursor. A ?sort= naming
anything outside the model's [ScaffoldSort] set falls back to the key ascending, so a client
cannot name an arbitrary column — the allow-list is compiled in, and in a JauntyQ store a validated
name selects which static .sql file runs rather than composing one.
A page is "the rows after this one in this order", not "rows 40 to 60". That is the point of the cursor: with an offset, a row inserted ahead of a reader pushes one row from the page they are on to the page they are about to request, and they never see it. The cost is that keyset paging cannot express "page 7", which is why the pager is Previous / N items / Next.
ScaffoldCursor is not a security boundary and is not signed. It is opaque so that no client
builds one, not so that none can. A forged cursor repositions a reader inside rows they were
already permitted to list, and its values reach the database as parameters. What is guaranteed is
that no string in ?after= can crash the list: TryDecode returns false for every malformed
shape, and the list renders from the beginning.
A ?sort= naming nothing sortable takes the direction down with it — the fallback is the key
ascending, whatever ?dir= said, because a direction applied to a column the reader did not
get is an ordering nobody asked for. No ?sort= at all is different: that is a request for the
default column, and ?dir=desc still applies to it.
Three obligations the framework cannot enforce, all stated on IScaffoldStore<T>.ListAsync and
all silent when broken:
- End every order with the key. A page boundary inside a block of equal sort values has no single answer without a tiebreaker, and the rows sitting there repeat or vanish.
- Fix where NULLs go on a nullable sorted column, in the query.
(author, id) > (@a, @id)isNULL— not true — for an author-less row, soWHEREdrops it and every page after the first omits every one of them.db/sample/queries/Articles/ListByAuthorAsc.sqlcarries the widened predicate. This is invisible on a table small enough to fit one page, which is why the reference app sorts by a nullable column on purpose. - Return at most
take - 1rows when you decline a backward cursor and fall back to the first page. The list asks for one row more than the page to learn whether another exists, and it trims a backward page from the tail — reading the direction from the cursor it issued, which it cannot know the store ignored. A fulltakecomes back as an overflowing backward page and its first row is trimmed away unseen. Both stores in this repo got this wrong first.
Wiring, and how to opt out of it
Two extension methods stand in for the ceremony. Neither hides anything: both are a handful of public calls, and writing those calls instead is a supported thing to do rather than a fallback.
builder.Services.AddScaffolding(); // AddAntiforgery() + AddAuthorization()
app.UseScaffolding(); // the four calls below, in this order
UseScaffolding() expands to exactly:
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.UseAntiforgeryRejection();
Write those four whenever the pipeline needs something between them — a rate limiter, a tenant resolver, a request logger. The order is the load-bearing part: antiforgery reads endpoint metadata so it must follow routing, and the rejection guard reads what antiforgery recorded so it must follow antiforgery.
UseAntiforgeryRejection() is the one with behaviour rather than ceremony.
UseAntiforgery() validates but does not reject: it records the failure on
IAntiforgeryValidationFeature and calls the next middleware anyway. The request reaches the
endpoint, the form reader throws a bare InvalidOperationException, and the caller gets a 500
where a 400 belongs. The guard turns that into a 400 and, more importantly, stops the endpoint
running at all. Safe to register unconditionally — a GET carries no such feature, so it is a
no-op.
Authentication is deliberately not in AddScaffolding(). Cookie name, login path and role
membership are the application's security posture, and a default supplied by a library is one
nobody reviews. A host that calls AddScaffolding() and no AddAuthentication gets scaffolded
routes that 401 — the correct failure. AddScaffolding_RegistersNoAuthenticationScheme asserts
the omission so it cannot be helpfully added later.
What the host still owns
Rate limiting. The scaffolded routes carry no policy.
Meaning. The generated form checks shape: a required text is present, a number parses, a date
reads. What a value means is the store's, and the store has one way to say no:
throw ScaffoldRefusedException("Slug 'aot' is already used.") from CreateAsync or
UpdateAsync. The generated handler catches that one type and re-renders the form with the
message where its own "Title is required." would go, the submitted values still in their inputs.
Any other exception is an error and is not caught: a store that wraps a broken connection in a
refusal turns an outage into a form message.
Running the demo
cd apps/sample && dotnet run
Then open http://localhost:5399/signin, which grants the admin role and redirects to /admin.
Every scaffolded Article route requires that role, so anywhere else is a 302 back to it. From
Visual Studio, F5 uses the same profile and opens the same URL.
The demo is HTTP only, deliberately. WebApplication.CreateSlimBuilder omits Kestrel's HTTPS
configuration — that is much of what makes it slim, since certificate loading drags in the
configuration binding an AOT publish would rather not have. Give it an https:// address and it
throws on startup, measured 2026-08-19:
System.InvalidOperationException: Call UseKestrelHttpsConfiguration() on IWebHostBuilder
to automatically enable HTTPS when an https:// address is used.
The fix is the address, not that call: adding HTTPS back would stop the sample demonstrating the
slim builder, and a deployment terminates TLS at the reverse proxy anyway. The default
launchSettings.json the SDK writes for a new project does specify an https:// URL, so the
one in apps/sample/Properties/ is checked in to override it.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Extrode.NativeWeb.Scaffold:
| Package | Downloads |
|---|---|
|
Extrode.NativeWeb.Permissions
NativeWeb framework: model permissions, groups, and the store contract the permission decisions read. |
GitHub repositories
This package is not used by any popular GitHub repositories.