Routing
A route ties a path to a view, optionally a controller, and the metadata that governs how it is authorized, compiled and updated.
Registering a route
UIApplicationBuilder.Route has three shapes:
application.Route<CounterView>("/");
application.Route<DashboardView, DashboardController>("/dashboard");
application.Route<DashboardView, DashboardController>("/dashboard", services => new DashboardView(services));
Route<TView>(route) registers a page with no controller — nothing to bind, so no state to observe.
Route<TView, TController>(route) is the usual case. A factory overload exists on both, for a view whose
constructor needs services the default parameterless Activator.CreateInstance cannot supply. Every overload
accepts an Action<UIRouteDefinitionBuilder> to configure the route's metadata:
application.Route<AdminView, AdminController>("/admin", route => route
.Require(new UIAccessRule { Roles = ["Admin"] })
.Identity("tenantId")
.CompilationMode(UIViewCompilationMode.Lazy)
);
UIRouteDefinitionBuilder:
AllowAnonymous(bool value = true)— lets the route resolve with no authenticated session.Require(UIAccessRule rule)— adds an access rule (roles/permissions, eachAny/All) the session must satisfy; call it more than once to add several rules, all of which must pass. The route's rules replace the ones the view's and controller's attributes carry, hold for every command on the page too, and close the route: it refuses an anonymous session whatever the attributes or the default policy say, unlessAllowAnonymous()is called on it as well.Identity(params string[] parameters)— names which navigation parameters are part of the route's address: two visits agreeing on every named parameter share the same runtime, and any other parameter travels without splitting it.CompilationMode(UIViewCompilationMode mode)—Startup(the default: compiled when the application is built) orLazy(compiled on first use and cached). Compiling is where a view's mistakes fail — an event that names a command its controller does not declare, for one — so underStartupevery such route fails together whenMapStandardUIWebAsyncruns, and a broken view fails the deployment rather than its first visitor. ALazyroute fails only when it is first opened. A view is compiled once and the compiled result shared — the HTTP shell render and the runtime's attach bind against the sameCompiledView, so a page whose content varies per request must vary through the controller, not by recompiling;DefaultErrorControllerreading its message from a navigation parameter is the idiom.FlushInterval(TimeSpan interval)— flushes the route's controller changes on an interval of its own instead of the application's.
A route's own Require(rule) or AllowAnonymous() wins over the attributes; an explicit [UIAuthorize]/[UIAllowAnonymous]
on the view or controller wins over UISecurityOptions.DefaultPolicy — see security. The two attributes never contradict each other on
one route: a [UIAllowAnonymous] on the view with a [UIAuthorize] on its controller, or the reverse, fails the startup.
Navigation parameters
UINavigationRequest is Route plus an optional Parameters dictionary (IReadOnlyDictionary<string, object?>). A controller reads it in OnNavigatedAsync, which every arrival runs (OnInitializeAsync sees only the first,
off Context.Handle.Instance.Navigation); TryGetParameter reads one as text, or as a primitive the framework's coercion knows:
protected override Task OnNavigatedAsync(UINavigationRequest navigation, CancellationToken cancellationToken)
{
if (navigation.TryGetParameter("message", out var message))
Message = message;
return Task.CompletedTask;
}
Claim what separates two pages of one route. A runtime is keyed by the session, the address and the tab, and
the address is the route plus the parameters named in Identity(...) — nothing else. One tab moving from /chat?c=1
to /chat?c=2 keeps one runtime with one state unless the route says Identity("c") (two tabs are two runtimes under the
default PerWindow); under PerClient, where the tab leaves the key, the two addresses are one runtime even in two tabs.
Nothing warns: the second page simply shows the first's state. Claim the parameter, and claim only what is identity — a tracking tag claimed strands a runtime of its own.
Context.Handle.Instance also carries Id (the transport connection), WindowId (the client's window — a browser tab) and
PageId. A parameter not named in Identity(...) is carried but does not separate one runtime from another.
Going between runtimes of one route loads no page. A link, a NavigateEffect or Back and Forward to an address of the same
route that differs in an Identity parameter — /chat?with=ann to /chat?with=bob — keeps the document: the page leaves the
runtime it holds over the connection it has and attaches to the other, built as a load would build it if none is kept, its
OnNavigatedAsync and OnAttachedAsync run as on a load. The other runtime's whole state is applied over the page; the sides stay
as they stand — a list of conversations keeps its place — and the content starts at its top, each list in it at its start or, held
to its end, at its end. Before it goes, the page sends what its fields still hold to the runtime it leaves, closes the dialogs that
runtime opened, and a background command raised there is cancelled, since the tab no longer stays on that runtime — a dropped connection alone
cancels none (work that must outlive the page is Context.Runtime.Start's). Until the other runtime has answered, the content takes no press or key, and nothing the runtime
left still sends reaches the page.
A page holding unsaved work asks before a link, an effect or Back and Forward takes it there, as before a load; Back and Forward
step back onto the page's own entry while the reader decides. A header's Back (NavigateBackEffect) is the browser's Back, and goes
the same way (interactions and effects). An address the reader may not see is never gone to in place: one the
route's filters or authorization turn to another route, or whose controller fails to start, loads the page, which shows what the
server renders there (a sign-in or an error page). A filter's redirect to another id of the same route attaches to that one.
The runtime left is kept for its retention, so going back finds its state as it was — but not its dialogs, which closed as the page
went — except under PerPage, which ends the runtimes a tab leaves: going back builds that one anew. A link to the same runtime, or
to another route, loads the page as before.
A parameter that is not identity reaches a kept runtime through OnNavigatedAsync. OnInitializeAsync runs once,
when the runtime is built; a tab that comes back to a runtime it kept — a reload, a link to the same address with another
?tab= — finds it initialized already. OnNavigatedAsync(navigation, cancellationToken) runs with the navigation the page
shows the runtime at — in the render that builds the runtime, so the first paint has it, and on every attach after that,
before OnAttachedAsync — so read a parameter there when it should act every time (see controllers).
Navigating from a command
A command returns a NavigateEffect(new UINavigationRequest { Route = "...", Parameters = ... }) to send the
client to another route — the client-effect vocabulary a command's UICommandResult carries, applied after
the command's own change set. A sign-in need not end this way: Context.SignInAsync moves the session to a new id
at once, and the page loads nothing until it has its new cookie, so the navigation that follows — to returnUrl, say — loads
under the signed-in session (security).
Keeping a page's state in its address
A filtered list, an open item or a chosen step belongs in the address when a reload, a bookmark or a link sent to someone should
arrive at it. A command writes it there with an effect rather than navigating, since a NavigateEffect loads the page again:
ReplaceAddressEffect(parameters)rewrites the current history entry's query — a filter or a sort, which is no place to go back to.PushAddressEffect(parameters)adds an entry — an item opened, which Back closes.
The route stays and the query becomes the parameters, written as a NavigateEffect's are (a collection repeats its key, a null is
left out). Nothing reloads, no runtime is built, and a page holding unsaved work does not ask. The controller reads the parameters
back where it reads any arrival's, in OnNavigatedAsync, and that hook also runs — on the same runtime, with no reload — when the
reader goes back or forward to another entry of the same route. The route's view filters run in UIViewRequestPhase.Attach first:
if a filter refuses or redirects, or an Identity parameter names another runtime, the browser falls back to an ordinary page load,
as it does for an entry of another route.
protected override Task OnNavigatedAsync(UINavigationRequest navigation, CancellationToken cancellationToken)
{
// Arrival and Back alike: no "message" closes the pane.
if (!navigation.TryGetParameter("message", out var id) || !Open(id))
Close();
return Task.CompletedTask;
}
[UICommand]
public UICommandResult OpenMessage(string id)
{
_ = Open(id);
// On a phone the pane stands under the list: brought into view, where beside the list nothing moves.
return UICommandResult.Ok(
[
new PushAddressEffect(new Dictionary<string, object?> { ["message"] = id }),
new ScrollToEffect("reading-pane")
]);
}
The browser keeps each entry's scroll position, so Back on a phone returns to the list where it was left, the pane closing under it.
Write only what differs from the page's defaults, so the bare route is the page as it opens, and read a value the page does not offer as its default. Three things to keep in mind:
- Not a parameter the route keys its runtime by. A parameter named in
Identity(...)makes another address and another runtime; written this way, the reload lands on a different runtime than the one that wrote it. To go to another runtime, link to its address: that loads no page either. - Under
PerClientthe state is every tab's. Back in one tab moves what every tab of the runtime shows, as a command in that tab would; the other tabs keep their own addresses. - The server does not hear the address change. The page's navigation stays the one it attached with, so a session that ends
sends the page to sign in with that address as its
returnUrl, not the query an effect wrote since.
Not found and error views
NotFoundView<TView>(route = "/not-found") and ErrorView<TView, TController>(route = "/error") (each with a
factory and a controller-backed overload) register the pages shown when a route is not registered
(UIRouteNotFoundException) or an unhandled exception occurs resolving or rendering a view; both are registered
anonymous. UIApplicationBuilder.Build fills in defaults for whichever of the two the application did not
register itself — the framework's own DefaultNotFoundView and DefaultErrorView/DefaultErrorController,
the latter reading the failure's text from its message navigation parameter only as a UIErrorDetail, handed over in-process
under IncludeExceptionDetail; a message in the address is anybody's words and is never shown. The not-found page standing
in for an address the application has not is answered with a 404; asked for by its own address, it is a page like any other.
View filters
IUIViewFilter.InvokeAsync(UIViewFilterContext context, Func<Task> next) wraps the resolution of a view — one
method covering before, after, short-circuit (don't call next) and exception handling. Register one for
every route with UIApplicationBuilder.AddViewFilter(filter) or AddViewFilter<TFilter>(order) (resolved
per request from a service scope of the request's own, disposed once the page is resolved, so a scoped filter — one
holding a DbContext — works and each request gets its own); attach one to a single route by putting an attribute that implements
IUIViewFilter on the view or controller class, ordered by IUIViewFilter.Order (ties break global, then
view, then controller). An attribute that needs constructor dependencies implements IUIViewFilterFactory
instead, and is built per request through CreateFilter(IServiceProvider services).
UIViewFilterContext carries Navigation, Route, Session, Services, Phase
(UIViewRequestPhase.Open/.Attach), the resolved Resolution (observation only, set after
next runs), and Redirect(UINavigationRequest) to divert the request — the host re-resolves from the top,
bounded the same way the error handler's redirects are.
A view filter runs twice per page load — once for the HTTP shell render and once when the client's live
connection attaches — and both are real entry points; guarding only one leaves the other unlocked. That is
correct for an access check and wrong for anything with a side effect, so a filter that must run once tests
context.Phase. The built-in route authorization check runs outermost (Order = int.MinValue), ahead of
every application and attribute filter, because a filter that ran before it could short-circuit past the
check.
Command filters
IUICommandFilter.InvokeAsync(UICommandFilterContext context, Func<Task> next) is the command-side mirror,
run by every command invocation: the built-in authorization check outermost, then
UIApplicationBuilder.AddCommandFilter(filter)/AddCommandFilter<TFilter>(order), then attributes on the
controller class and the command method (IUICommandFilterFactory for one needing services).
AddCommandFilter<TFilter> resolves the filter on every invocation from the page's service scope, the one its controller
was built from: registered transient it is built per command, registered scoped it is the page's own and shares the
controller's scoped services. A disposable transient stays held by that scope until the page ends, so a filter built per
command is better not disposable.
UICommandFilterContext carries Command (IUICommandMetadata), Arguments, Handle, Route, Services,
Invoked (true only once next has actually run) and Result — replace it after next to add effects, or
set it directly without calling next to short-circuit. A filter cannot undo a command: once next returns,
its writes are already in the change buffer.
AllowAnonymous and a command's own route
IUICommandMetadata.AllowAnonymous is bool?; null (the default, with no attribute on the command) makes
the command follow UIContext.Route.AllowAnonymous — one DefaultPolicy therefore governs a page and every
command on it unless a command overrides it explicitly with its own [UIAuthorize]/[UIAllowAnonymous] on the
method (the controller class's attributes reach the command through the route, never past it). A command carrying both, or a
[UIAuthorize] whose overridden declaration carries [UIAllowAnonymous], fails the startup.
See security for how access rules are evaluated and how a refusal is routed.