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: MIT5---67# dotnet-blazor-patterns89Blazor hosting models, render modes, project setup, routing, enhanced navigation, streaming rendering, and AOT-safe10patterns. Covers all five hosting models (InteractiveServer, InteractiveWebAssembly, InteractiveAuto, Static SSR,11Hybrid) with trade-off analysis for each.1213## Scope1415- Blazor Web App project setup and configuration16- Hosting model selection (Server, WASM, Auto, SSR, Hybrid)17- Render mode configuration (global, per-page, per-component)18- Routing and enhanced navigation19- Streaming rendering and prerendering20- AOT-safe Blazor patterns2122## Out of scope2324- Component architecture (lifecycle, state, JS interop) -- see [skill:dotnet-blazor-components]25- Authentication across hosting models -- see [skill:dotnet-blazor-auth]26- bUnit component testing -- see [skill:dotnet-blazor-testing]27- Standalone SignalR patterns -- see [skill:dotnet-realtime-communication]28- Browser-based E2E testing -- see [skill:dotnet-playwright]29- UI framework selection decision tree -- see [skill:dotnet-ui-chooser]3031Cross-references: [skill:dotnet-blazor-components] for component architecture, [skill:dotnet-blazor-auth] for32authentication, [skill:dotnet-blazor-testing] for bUnit testing, [skill:dotnet-realtime-communication] for standalone33SignalR, [skill:dotnet-playwright] for E2E testing, [skill:dotnet-ui-chooser] for framework selection,34[skill:dotnet-accessibility] for accessibility patterns (ARIA, keyboard nav, screen readers).3536---3738## Hosting Models & Render Modes3940Blazor Web App (.NET 8+) is the default project template, replacing the separate Blazor Server and Blazor WebAssembly41templates. Render modes can be set globally, per-page, or per-component.4243### Render Mode Overview4445| Render Mode | Attribute | Interactivity | Connection | Best For |46| ---------------------- | ------------------------------------ | --------------------------------------------- | ---------------------------- | -------------------------------------------------------------- |47| Static SSR | (none / default) | None -- server renders HTML, no interactivity | HTTP request only | Content pages, SEO, forms with minimal interactivity |48| InteractiveServer | `@rendermode InteractiveServer` | Full | SignalR circuit | Low-latency interactivity, full server access, small user base |49| InteractiveWebAssembly | `@rendermode InteractiveWebAssembly` | Full (after download) | None (runs in browser) | Offline-capable, large user base, reduced server load |50| InteractiveAuto | `@rendermode InteractiveAuto` | Full | SignalR initially, then WASM | Best of both -- immediate interactivity, eventual client-side |51| Blazor Hybrid | `BlazorWebView` in MAUI/WPF/WinForms | Full (native) | None (runs in-process) | Desktop/mobile apps with web UI, native API access |5253### Per-Mode Trade-offs5455| Concern | Static SSR | InteractiveServer | InteractiveWebAssembly | InteractiveAuto | Hybrid |56| -------------------- | ------------ | ------------------- | ------------------------- | ------------------- | --------------- |57| First load | Fast | Fast | Slow (WASM download) | Fast (Server first) | Instant (local) |58| Server resources | Minimal | Per-user circuit | None after download | Circuit then none | None |59| Offline support | No | No | Yes | Partial | Yes |60| Full .NET API access | Yes (server) | Yes (server) | Limited (browser sandbox) | Varies by phase | Yes (native) |61| Scalability | High | Limited by circuits | High | High (after WASM) | N/A (local) |62| SEO | Yes | Prerender | Prerender | Prerender | N/A |6364### Setting Render Modes6566**Global (App.razor):**6768````razor6970<!-- Sets default render mode for all pages -->71<Routes @rendermode="InteractiveServer" />7273```text7475**Per-page:**7677```razor7879@page "/dashboard"80@rendermode InteractiveServer8182<h1>Dashboard</h1>8384```text8586**Per-component:**8788```razor8990<Counter @rendermode="InteractiveWebAssembly" />9192```text9394**Gotcha:** Without an explicit render mode boundary, a child component cannot request a more interactive render mode95than its parent. However, interactive islands are supported: you can place an `@rendermode` attribute on a component96embedded in a Static SSR page to create a render mode boundary, enabling interactive children under otherwise static97content.9899---100101## Project Setup102103### Blazor Web App (Default Template)104105```bash106107# Creates a Blazor Web App with InteractiveServer render mode108dotnet new blazor -n MyApp109110# With specific interactivity options111dotnet new blazor -n MyApp --interactivity Auto # InteractiveAuto112dotnet new blazor -n MyApp --interactivity WebAssembly # InteractiveWebAssembly113dotnet new blazor -n MyApp --interactivity Server # InteractiveServer (default)114dotnet new blazor -n MyApp --interactivity None # Static SSR only115116```text117118### Blazor Web App Project Structure119120```text121122MyApp/123 MyApp/ # Server project124 Program.cs # Host builder, services, middleware125 Components/126 App.razor # Root component (sets global render mode)127 Routes.razor # Router component128 Layout/129 MainLayout.razor # Main layout130 Pages/131 Home.razor # Static SSR by default132 Counter.razor # Can set per-page render mode133 MyApp.Client/ # Client project (only if WASM or Auto)134 Pages/135 Counter.razor # Components that run in browser136 Program.cs # WASM entry point137138```csharp139140When using InteractiveAuto or InteractiveWebAssembly, components that must run in the browser go in the `.Client`141project. Components in the server project run on the server only.142143### Blazor Hybrid Setup (MAUI)144145```xml146147<!-- .csproj for MAUI Blazor Hybrid -->148<Project Sdk="Microsoft.NET.Sdk.Razor">149 <PropertyGroup>150 <TargetFrameworks>net10.0-android;net10.0-ios;net10.0-maccatalyst</TargetFrameworks>151 <OutputType>Exe</OutputType>152 <UseMaui>true</UseMaui>153 </PropertyGroup>154</Project>155156```text157158```csharp159160// MainPage.xaml.cs hosts BlazorWebView161public partial class MainPage : ContentPage162{163 public MainPage()164 {165 InitializeComponent();166 }167}168169```text170171```xml172173<!-- MainPage.xaml -->174<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"175 xmlns:b="clr-namespace:Microsoft.AspNetCore.Components.WebView.Maui;assembly=Microsoft.AspNetCore.Components.WebView.Maui">176 <b:BlazorWebView HostPage="wwwroot/index.html">177 <b:BlazorWebView.RootComponents>178 <b:RootComponent Selector="#app" ComponentType="{x:Type local:Routes}" />179 </b:BlazorWebView.RootComponents>180 </b:BlazorWebView>181</ContentPage>182183```text184185---186187## Routing188189### Basic Routing190191```razor192193@page "/products"194@page "/products/{Category}"195196<h1>Products</h1>197@if (!string.IsNullOrEmpty(Category))198{199 <p>Category: @Category</p>200}201202@code {203 [Parameter]204 public string? Category { get; set; }205}206207```text208209### Route Constraints210211```razor212213@page "/products/{Id:int}"214@page "/orders/{Date:datetime}"215@page "/search/{Query:minlength(3)}"216217@code {218 [Parameter] public int Id { get; set; }219 [Parameter] public DateTime Date { get; set; }220 [Parameter] public string Query { get; set; } = "";221}222223```text224225### Query String Parameters226227```razor228229@page "/search"230231@code {232 [SupplyParameterFromQuery]233 public string? Term { get; set; }234235 [SupplyParameterFromQuery(Name = "page")]236 public int CurrentPage { get; set; } = 1;237}238239```text240241### NavigationManager242243```csharp244245@inject NavigationManager Navigation246247// Programmatic navigation248Navigation.NavigateTo("/products/electronics");249250// With query string251Navigation.NavigateTo("/search?term=keyboard&page=2");252253// Force full page reload (bypasses enhanced navigation)254Navigation.NavigateTo("/external-page", forceLoad: true);255256```text257258---259260## Enhanced Navigation (.NET 8+)261262Enhanced navigation intercepts link clicks and form submissions to update only the changed DOM content, preserving page263state and avoiding full page reloads. This applies to Static SSR and prerendered pages.264265### How It Works2662671. User clicks a link within the Blazor app2682. Blazor intercepts the navigation2693. A fetch request loads the new page content2704. Blazor patches the DOM with only the differences2715. Scroll position and focus state are preserved272273### Opting Out274275```razor276277<!-- Disable enhanced navigation for a specific link -->278<a href="/legacy-page" data-enhance-nav="false">Legacy Page</a>279280<!-- Disable enhanced form handling for a specific form -->281<form method="post" data-enhance="false">282 ...283</form>284285```text286287**Gotcha:** Enhanced navigation may interfere with third-party JavaScript libraries that expect full page loads. Use288`data-enhance-nav="false"` on links that navigate to pages with JS that initializes on `DOMContentLoaded`.289290---291292## Streaming Rendering (.NET 8+)293294Streaming rendering sends initial HTML immediately (with placeholder content), then streams updates as async operations295complete. Useful for pages with slow data sources.296297```razor298299@page "/dashboard"300@attribute [StreamRendering]301302<h1>Dashboard</h1>303304@if (orders is null)305{306 <p>Loading orders...</p>307}308else309{310 <table>311 @foreach (var order in orders)312 {313 <tr><td>@order.Id</td><td>@order.Total</td></tr>314 }315 </table>316}317318@code {319 private List<OrderDto>? orders;320321 protected override async Task OnInitializedAsync()322 {323 // Initial HTML sent immediately with "Loading orders..."324 // Updated HTML streamed when this completes325 orders = await OrderService.GetRecentOrdersAsync();326 }327}328329```text330331**Behavior per render mode:**332333- **Static SSR:** Streaming rendering sends the initial response, then patches the DOM via chunked transfer encoding.334 The page is not interactive.335- **InteractiveServer/WebAssembly/Auto:** Streaming rendering is less impactful because components re-render336 automatically after async operations. The `[StreamRendering]` attribute primarily benefits the prerender phase.337338---339340## AOT-Safe Patterns341342When targeting Blazor WebAssembly with Native AOT (ahead-of-time compilation) or IL trimming, avoid patterns that rely343on runtime reflection.344345### Source-Generator-First Serialization346347```csharp348349// CORRECT: Source-generated JSON serialization (AOT-compatible)350[JsonSerializable(typeof(ProductDto))]351[JsonSerializable(typeof(List<ProductDto>))]352[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]353public partial class AppJsonContext : JsonSerializerContext { }354355// Register in Program.cs356builder.Services.ConfigureHttpJsonOptions(options =>357{358 options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default);359});360361// Usage in HttpClient calls362var products = await Http.GetFromJsonAsync<List<ProductDto>>(363 "/api/products",364 AppJsonContext.Default.ListProductDto);365366```json367368```csharp369370// WRONG: Reflection-based serialization (fails under AOT/trimming)371var products = await Http.GetFromJsonAsync<List<ProductDto>>("/api/products");372373```csharp374375### Trim-Safe JS Interop376377## Detailed Examples378379See [references/detailed-examples.md](references/detailed-examples.md) for complete code samples and advanced patterns.