dotnet-blazor-patterns
Blazor hosting models, render modes, project setup, routing, enhanced navigation, streaming rendering, and AOT-safe
patterns. Covers all five hosting models (InteractiveServer, InteractiveWebAssembly, InteractiveAuto, Static SSR,
Hybrid) with trade-off analysis for each.
Scope
- Blazor Web App project setup and configuration
- Hosting model selection (Server, WASM, Auto, SSR, Hybrid)
- Render mode configuration (global, per-page, per-component)
- Routing and enhanced navigation
- Streaming rendering and prerendering
- AOT-safe Blazor patterns
Out of scope
- Component architecture (lifecycle, state, JS interop) -- see [skill:dotnet-blazor-components]
- Authentication across hosting models -- see [skill:dotnet-blazor-auth]
- bUnit component testing -- see [skill:dotnet-blazor-testing]
- Standalone SignalR patterns -- see [skill:dotnet-realtime-communication]
- Browser-based E2E testing -- see [skill:dotnet-playwright]
- UI framework selection decision tree -- see [skill:dotnet-ui-chooser]
Cross-references: [skill:dotnet-blazor-components] for component architecture, [skill:dotnet-blazor-auth] for
authentication, [skill:dotnet-blazor-testing] for bUnit testing, [skill:dotnet-realtime-communication] for standalone
SignalR, [skill:dotnet-playwright] for E2E testing, [skill:dotnet-ui-chooser] for framework selection,
[skill:dotnet-accessibility] for accessibility patterns (ARIA, keyboard nav, screen readers).
Hosting Models & Render Modes
Blazor Web App (.NET 8+) is the default project template, replacing the separate Blazor Server and Blazor WebAssembly
templates. Render modes can be set globally, per-page, or per-component.
Render Mode Overview
| Render Mode |
Attribute |
Interactivity |
Connection |
Best For |
| Static SSR |
(none / default) |
None -- server renders HTML, no interactivity |
HTTP request only |
Content pages, SEO, forms with minimal interactivity |
| InteractiveServer |
@rendermode InteractiveServer |
Full |
SignalR circuit |
Low-latency interactivity, full server access, small user base |
| InteractiveWebAssembly |
@rendermode InteractiveWebAssembly |
Full (after download) |
None (runs in browser) |
Offline-capable, large user base, reduced server load |
| InteractiveAuto |
@rendermode InteractiveAuto |
Full |
SignalR initially, then WASM |
Best of both -- immediate interactivity, eventual client-side |
| Blazor Hybrid |
BlazorWebView in MAUI/WPF/WinForms |
Full (native) |
None (runs in-process) |
Desktop/mobile apps with web UI, native API access |
Per-Mode Trade-offs
| Concern |
Static SSR |
InteractiveServer |
InteractiveWebAssembly |
InteractiveAuto |
Hybrid |
| First load |
Fast |
Fast |
Slow (WASM download) |
Fast (Server first) |
Instant (local) |
| Server resources |
Minimal |
Per-user circuit |
None after download |
Circuit then none |
None |
| Offline support |
No |
No |
Yes |
Partial |
Yes |
| Full .NET API access |
Yes (server) |
Yes (server) |
Limited (browser sandbox) |
Varies by phase |
Yes (native) |
| Scalability |
High |
Limited by circuits |
High |
High (after WASM) |
N/A (local) |
| SEO |
Yes |
Prerender |
Prerender |
Prerender |
N/A |
Setting Render Modes
Global (App.razor):
<!-- Sets default render mode for all pages -->
<Routes @rendermode="InteractiveServer" />
```text
**Per-page:**
```razor
@page "/dashboard"
@rendermode InteractiveServer
<h1>Dashboard</h1>
```text
**Per-component:**
```razor
<Counter @rendermode="InteractiveWebAssembly" />
```text
**Gotcha:** Without an explicit render mode boundary, a child component cannot request a more interactive render mode
than its parent. However, interactive islands are supported: you can place an `@rendermode` attribute on a component
embedded in a Static SSR page to create a render mode boundary, enabling interactive children under otherwise static
content.
---
## Project Setup
### Blazor Web App (Default Template)
```bash
# Creates a Blazor Web App with InteractiveServer render mode
dotnet new blazor -n MyApp
# With specific interactivity options
dotnet new blazor -n MyApp --interactivity Auto # InteractiveAuto
dotnet new blazor -n MyApp --interactivity WebAssembly # InteractiveWebAssembly
dotnet new blazor -n MyApp --interactivity Server # InteractiveServer (default)
dotnet new blazor -n MyApp --interactivity None # Static SSR only
```text
### Blazor Web App Project Structure
```text
MyApp/
MyApp/ # Server project
Program.cs # Host builder, services, middleware
Components/
App.razor # Root component (sets global render mode)
Routes.razor # Router component
Layout/
MainLayout.razor # Main layout
Pages/
Home.razor # Static SSR by default
Counter.razor # Can set per-page render mode
MyApp.Client/ # Client project (only if WASM or Auto)
Pages/
Counter.razor # Components that run in browser
Program.cs # WASM entry point
```csharp
When using InteractiveAuto or InteractiveWebAssembly, components that must run in the browser go in the `.Client`
project. Components in the server project run on the server only.
### Blazor Hybrid Setup (MAUI)
```xml
<!-- .csproj for MAUI Blazor Hybrid -->
<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<TargetFrameworks>net10.0-android;net10.0-ios;net10.0-maccatalyst</TargetFrameworks>
<OutputType>Exe</OutputType>
<UseMaui>true</UseMaui>
</PropertyGroup>
</Project>
```text
```csharp
// MainPage.xaml.cs hosts BlazorWebView
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
}
```text
```xml
<!-- MainPage.xaml -->
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:b="clr-namespace:Microsoft.AspNetCore.Components.WebView.Maui;assembly=Microsoft.AspNetCore.Components.WebView.Maui">
<b:BlazorWebView HostPage="wwwroot/index.html">
<b:BlazorWebView.RootComponents>
<b:RootComponent Selector="#app" ComponentType="{x:Type local:Routes}" />
</b:BlazorWebView.RootComponents>
</b:BlazorWebView>
</ContentPage>
```text
---
## Routing
### Basic Routing
```razor
@page "/products"
@page "/products/{Category}"
<h1>Products</h1>
@if (!string.IsNullOrEmpty(Category))
{
<p>Category: @Category</p>
}
@code {
[Parameter]
public string? Category { get; set; }
}
```text
### Route Constraints
```razor
@page "/products/{Id:int}"
@page "/orders/{Date:datetime}"
@page "/search/{Query:minlength(3)}"
@code {
[Parameter] public int Id { get; set; }
[Parameter] public DateTime Date { get; set; }
[Parameter] public string Query { get; set; } = "";
}
```text
### Query String Parameters
```razor
@page "/search"
@code {
[SupplyParameterFromQuery]
public string? Term { get; set; }
[SupplyParameterFromQuery(Name = "page")]
public int CurrentPage { get; set; } = 1;
}
```text
### NavigationManager
```csharp
@inject NavigationManager Navigation
// Programmatic navigation
Navigation.NavigateTo("/products/electronics");
// With query string
Navigation.NavigateTo("/search?term=keyboard&page=2");
// Force full page reload (bypasses enhanced navigation)
Navigation.NavigateTo("/external-page", forceLoad: true);
```text
---
## Enhanced Navigation (.NET 8+)
Enhanced navigation intercepts link clicks and form submissions to update only the changed DOM content, preserving page
state and avoiding full page reloads. This applies to Static SSR and prerendered pages.
### How It Works
1. User clicks a link within the Blazor app
2. Blazor intercepts the navigation
3. A fetch request loads the new page content
4. Blazor patches the DOM with only the differences
5. Scroll position and focus state are preserved
### Opting Out
```razor
<!-- Disable enhanced navigation for a specific link -->
<a href="/legacy-page" data-enhance-nav="false">Legacy Page</a>
<!-- Disable enhanced form handling for a specific form -->
<form method="post" data-enhance="false">
...
</form>
```text
**Gotcha:** Enhanced navigation may interfere with third-party JavaScript libraries that expect full page loads. Use
`data-enhance-nav="false"` on links that navigate to pages with JS that initializes on `DOMContentLoaded`.
---
## Streaming Rendering (.NET 8+)
Streaming rendering sends initial HTML immediately (with placeholder content), then streams updates as async operations
complete. Useful for pages with slow data sources.
```razor
@page "/dashboard"
@attribute [StreamRendering]
<h1>Dashboard</h1>
@if (orders is null)
{
<p>Loading orders...</p>
}
else
{
<table>
@foreach (var order in orders)
{
<tr><td>@order.Id</td><td>@order.Total</td></tr>
}
</table>
}
@code {
private List<OrderDto>? orders;
protected override async Task OnInitializedAsync()
{
// Initial HTML sent immediately with "Loading orders..."
// Updated HTML streamed when this completes
orders = await OrderService.GetRecentOrdersAsync();
}
}
```text
**Behavior per render mode:**
- **Static SSR:** Streaming rendering sends the initial response, then patches the DOM via chunked transfer encoding.
The page is not interactive.
- **InteractiveServer/WebAssembly/Auto:** Streaming rendering is less impactful because components re-render
automatically after async operations. The `[StreamRendering]` attribute primarily benefits the prerender phase.
---
## AOT-Safe Patterns
When targeting Blazor WebAssembly with Native AOT (ahead-of-time compilation) or IL trimming, avoid patterns that rely
on runtime reflection.
### Source-Generator-First Serialization
```csharp
// CORRECT: Source-generated JSON serialization (AOT-compatible)
[JsonSerializable(typeof(ProductDto))]
[JsonSerializable(typeof(List<ProductDto>))]
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
public partial class AppJsonContext : JsonSerializerContext { }
// Register in Program.cs
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);
});
// Usage in HttpClient calls
var products = await Http.GetFromJsonAsync<List<ProductDto>>(
"/api/products",
AppJsonContext.Default.ListProductDto);
```json
```csharp
// WRONG: Reflection-based serialization (fails under AOT/trimming)
var products = await Http.GetFromJsonAsync<List<ProductDto>>("/api/products");
```csharp
### Trim-Safe JS Interop
## Detailed Examples
See [references/detailed-examples.md](references/detailed-examples.md) for complete code samples and advanced patterns.
1---2name: dotnet-blazor-patterns3description: Architects Blazor apps. Hosting models, render modes, routing, streaming, prerender.4license: MIT5targets: ['*']6category: ui-frameworks7subcategory: blazor8tags:9 - platforms10 - dotnet11 - skill12 - blazor13 - web14version: '1.0.0'15author: 'dotnet-agent-harness'16invocable: true17related_skills:18 - dotnet-blazor-components19 - dotnet-blazor-auth20 - dotnet-blazor-testing21claudecode:22 allowed-tools: ['Read', 'Grep', 'Glob', 'Bash', 'Write', 'Edit']23codexcli:24 short-description: '.NET skill guidance for blazor tasks'25opencode:26 allowed-tools: ['Read', 'Grep', 'Glob', 'Bash', 'Write', 'Edit']27copilot: {}28geminicli: {}29antigravity: {}30---3132# dotnet-blazor-patterns3334Blazor hosting models, render modes, project setup, routing, enhanced navigation, streaming rendering, and AOT-safe35patterns. Covers all five hosting models (InteractiveServer, InteractiveWebAssembly, InteractiveAuto, Static SSR,36Hybrid) with trade-off analysis for each.3738## Scope3940- Blazor Web App project setup and configuration41- Hosting model selection (Server, WASM, Auto, SSR, Hybrid)42- Render mode configuration (global, per-page, per-component)43- Routing and enhanced navigation44- Streaming rendering and prerendering45- AOT-safe Blazor patterns4647## Out of scope4849- Component architecture (lifecycle, state, JS interop) -- see [skill:dotnet-blazor-components]50- Authentication across hosting models -- see [skill:dotnet-blazor-auth]51- bUnit component testing -- see [skill:dotnet-blazor-testing]52- Standalone SignalR patterns -- see [skill:dotnet-realtime-communication]53- Browser-based E2E testing -- see [skill:dotnet-playwright]54- UI framework selection decision tree -- see [skill:dotnet-ui-chooser]5556Cross-references: [skill:dotnet-blazor-components] for component architecture, [skill:dotnet-blazor-auth] for57authentication, [skill:dotnet-blazor-testing] for bUnit testing, [skill:dotnet-realtime-communication] for standalone58SignalR, [skill:dotnet-playwright] for E2E testing, [skill:dotnet-ui-chooser] for framework selection,59[skill:dotnet-accessibility] for accessibility patterns (ARIA, keyboard nav, screen readers).6061---6263## Hosting Models & Render Modes6465Blazor Web App (.NET 8+) is the default project template, replacing the separate Blazor Server and Blazor WebAssembly66templates. Render modes can be set globally, per-page, or per-component.6768### Render Mode Overview6970| Render Mode | Attribute | Interactivity | Connection | Best For |71| ---------------------- | ------------------------------------ | --------------------------------------------- | ---------------------------- | -------------------------------------------------------------- |72| Static SSR | (none / default) | None -- server renders HTML, no interactivity | HTTP request only | Content pages, SEO, forms with minimal interactivity |73| InteractiveServer | `@rendermode InteractiveServer` | Full | SignalR circuit | Low-latency interactivity, full server access, small user base |74| InteractiveWebAssembly | `@rendermode InteractiveWebAssembly` | Full (after download) | None (runs in browser) | Offline-capable, large user base, reduced server load |75| InteractiveAuto | `@rendermode InteractiveAuto` | Full | SignalR initially, then WASM | Best of both -- immediate interactivity, eventual client-side |76| Blazor Hybrid | `BlazorWebView` in MAUI/WPF/WinForms | Full (native) | None (runs in-process) | Desktop/mobile apps with web UI, native API access |7778### Per-Mode Trade-offs7980| Concern | Static SSR | InteractiveServer | InteractiveWebAssembly | InteractiveAuto | Hybrid |81| -------------------- | ------------ | ------------------- | ------------------------- | ------------------- | --------------- |82| First load | Fast | Fast | Slow (WASM download) | Fast (Server first) | Instant (local) |83| Server resources | Minimal | Per-user circuit | None after download | Circuit then none | None |84| Offline support | No | No | Yes | Partial | Yes |85| Full .NET API access | Yes (server) | Yes (server) | Limited (browser sandbox) | Varies by phase | Yes (native) |86| Scalability | High | Limited by circuits | High | High (after WASM) | N/A (local) |87| SEO | Yes | Prerender | Prerender | Prerender | N/A |8889### Setting Render Modes9091**Global (App.razor):**9293````razor9495<!-- Sets default render mode for all pages -->96<Routes @rendermode="InteractiveServer" />9798```text99100**Per-page:**101102```razor103104@page "/dashboard"105@rendermode InteractiveServer106107<h1>Dashboard</h1>108109```text110111**Per-component:**112113```razor114115<Counter @rendermode="InteractiveWebAssembly" />116117```text118119**Gotcha:** Without an explicit render mode boundary, a child component cannot request a more interactive render mode120than its parent. However, interactive islands are supported: you can place an `@rendermode` attribute on a component121embedded in a Static SSR page to create a render mode boundary, enabling interactive children under otherwise static122content.123124---125126## Project Setup127128### Blazor Web App (Default Template)129130```bash131132# Creates a Blazor Web App with InteractiveServer render mode133dotnet new blazor -n MyApp134135# With specific interactivity options136dotnet new blazor -n MyApp --interactivity Auto # InteractiveAuto137dotnet new blazor -n MyApp --interactivity WebAssembly # InteractiveWebAssembly138dotnet new blazor -n MyApp --interactivity Server # InteractiveServer (default)139dotnet new blazor -n MyApp --interactivity None # Static SSR only140141```text142143### Blazor Web App Project Structure144145```text146147MyApp/148 MyApp/ # Server project149 Program.cs # Host builder, services, middleware150 Components/151 App.razor # Root component (sets global render mode)152 Routes.razor # Router component153 Layout/154 MainLayout.razor # Main layout155 Pages/156 Home.razor # Static SSR by default157 Counter.razor # Can set per-page render mode158 MyApp.Client/ # Client project (only if WASM or Auto)159 Pages/160 Counter.razor # Components that run in browser161 Program.cs # WASM entry point162163```csharp164165When using InteractiveAuto or InteractiveWebAssembly, components that must run in the browser go in the `.Client`166project. Components in the server project run on the server only.167168### Blazor Hybrid Setup (MAUI)169170```xml171172<!-- .csproj for MAUI Blazor Hybrid -->173<Project Sdk="Microsoft.NET.Sdk.Razor">174 <PropertyGroup>175 <TargetFrameworks>net10.0-android;net10.0-ios;net10.0-maccatalyst</TargetFrameworks>176 <OutputType>Exe</OutputType>177 <UseMaui>true</UseMaui>178 </PropertyGroup>179</Project>180181```text182183```csharp184185// MainPage.xaml.cs hosts BlazorWebView186public partial class MainPage : ContentPage187{188 public MainPage()189 {190 InitializeComponent();191 }192}193194```text195196```xml197198<!-- MainPage.xaml -->199<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"200 xmlns:b="clr-namespace:Microsoft.AspNetCore.Components.WebView.Maui;assembly=Microsoft.AspNetCore.Components.WebView.Maui">201 <b:BlazorWebView HostPage="wwwroot/index.html">202 <b:BlazorWebView.RootComponents>203 <b:RootComponent Selector="#app" ComponentType="{x:Type local:Routes}" />204 </b:BlazorWebView.RootComponents>205 </b:BlazorWebView>206</ContentPage>207208```text209210---211212## Routing213214### Basic Routing215216```razor217218@page "/products"219@page "/products/{Category}"220221<h1>Products</h1>222@if (!string.IsNullOrEmpty(Category))223{224 <p>Category: @Category</p>225}226227@code {228 [Parameter]229 public string? Category { get; set; }230}231232```text233234### Route Constraints235236```razor237238@page "/products/{Id:int}"239@page "/orders/{Date:datetime}"240@page "/search/{Query:minlength(3)}"241242@code {243 [Parameter] public int Id { get; set; }244 [Parameter] public DateTime Date { get; set; }245 [Parameter] public string Query { get; set; } = "";246}247248```text249250### Query String Parameters251252```razor253254@page "/search"255256@code {257 [SupplyParameterFromQuery]258 public string? Term { get; set; }259260 [SupplyParameterFromQuery(Name = "page")]261 public int CurrentPage { get; set; } = 1;262}263264```text265266### NavigationManager267268```csharp269270@inject NavigationManager Navigation271272// Programmatic navigation273Navigation.NavigateTo("/products/electronics");274275// With query string276Navigation.NavigateTo("/search?term=keyboard&page=2");277278// Force full page reload (bypasses enhanced navigation)279Navigation.NavigateTo("/external-page", forceLoad: true);280281```text282283---284285## Enhanced Navigation (.NET 8+)286287Enhanced navigation intercepts link clicks and form submissions to update only the changed DOM content, preserving page288state and avoiding full page reloads. This applies to Static SSR and prerendered pages.289290### How It Works2912921. User clicks a link within the Blazor app2932. Blazor intercepts the navigation2943. A fetch request loads the new page content2954. Blazor patches the DOM with only the differences2965. Scroll position and focus state are preserved297298### Opting Out299300```razor301302<!-- Disable enhanced navigation for a specific link -->303<a href="/legacy-page" data-enhance-nav="false">Legacy Page</a>304305<!-- Disable enhanced form handling for a specific form -->306<form method="post" data-enhance="false">307 ...308</form>309310```text311312**Gotcha:** Enhanced navigation may interfere with third-party JavaScript libraries that expect full page loads. Use313`data-enhance-nav="false"` on links that navigate to pages with JS that initializes on `DOMContentLoaded`.314315---316317## Streaming Rendering (.NET 8+)318319Streaming rendering sends initial HTML immediately (with placeholder content), then streams updates as async operations320complete. Useful for pages with slow data sources.321322```razor323324@page "/dashboard"325@attribute [StreamRendering]326327<h1>Dashboard</h1>328329@if (orders is null)330{331 <p>Loading orders...</p>332}333else334{335 <table>336 @foreach (var order in orders)337 {338 <tr><td>@order.Id</td><td>@order.Total</td></tr>339 }340 </table>341}342343@code {344 private List<OrderDto>? orders;345346 protected override async Task OnInitializedAsync()347 {348 // Initial HTML sent immediately with "Loading orders..."349 // Updated HTML streamed when this completes350 orders = await OrderService.GetRecentOrdersAsync();351 }352}353354```text355356**Behavior per render mode:**357358- **Static SSR:** Streaming rendering sends the initial response, then patches the DOM via chunked transfer encoding.359 The page is not interactive.360- **InteractiveServer/WebAssembly/Auto:** Streaming rendering is less impactful because components re-render361 automatically after async operations. The `[StreamRendering]` attribute primarily benefits the prerender phase.362363---364365## AOT-Safe Patterns366367When targeting Blazor WebAssembly with Native AOT (ahead-of-time compilation) or IL trimming, avoid patterns that rely368on runtime reflection.369370### Source-Generator-First Serialization371372```csharp373374// CORRECT: Source-generated JSON serialization (AOT-compatible)375[JsonSerializable(typeof(ProductDto))]376[JsonSerializable(typeof(List<ProductDto>))]377[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]378public partial class AppJsonContext : JsonSerializerContext { }379380// Register in Program.cs381builder.Services.ConfigureHttpJsonOptions(options =>382{383 options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);384});385386// Usage in HttpClient calls387var products = await Http.GetFromJsonAsync<List<ProductDto>>(388 "/api/products",389 AppJsonContext.Default.ListProductDto);390391```json392393```csharp394395// WRONG: Reflection-based serialization (fails under AOT/trimming)396var products = await Http.GetFromJsonAsync<List<ProductDto>>("/api/products");397398```csharp399400### Trim-Safe JS Interop401402## Detailed Examples403404See [references/detailed-examples.md](references/detailed-examples.md) for complete code samples and advanced patterns.