Agent Skillsdotnet/skills › support-prerendering

support-prerendering

GitHub

解决 Blazor 预渲染与交互模式切换时的数据重复加载、UI闪烁及状态丢失问题。提供状态持久化方案,支持禁用预渲染或检测预渲染状态,优化组件生命周期行为。

plugins/dotnet-blazor/skills/support-prerendering/SKILL.md dotnet/skills

Trigger Scenarios

修复预渲染导致的数据重复请求 解决预渲染到交互模式的 UI 闪烁 处理预渲染期间的空引用异常 跨预渲染阶段持久化组件状态

Install

npx skills add dotnet/skills --skill support-prerendering -g -y
More Options

Non-standard path

npx skills add https://github.com/dotnet/skills/tree/main/plugins/dotnet-blazor/skills/support-prerendering -g -y

Use without installing

npx skills use dotnet/skills@support-prerendering

指定 Agent (Claude Code)

npx skills add dotnet/skills --skill support-prerendering -a claude-code -g -y

安装 repo 全部 skill

npx skills add dotnet/skills --all -g -y

预览 repo 内 skill

npx skills add dotnet/skills --list

SKILL.md

Frontmatter
{
    "name": "support-prerendering",
    "license": "MIT",
    "description": "Make interactive Blazor components work correctly with prerendering. USE FOR fixing duplicate data loads, UI flicker during prerender-to-interactive handoff, null references during prerender, persisting state across prerender, disabling prerendering, excluding pages from interactive routing, or detecting whether a component is currently prerendering. DO NOT USE for choosing which render mode to use (see create-blazor-project) or general component authoring (see author-component)."
}

Support Prerendering

How Prerendering Works

Prerendering is on by default for all interactive render modes. The server renders the component as static HTML and ships it to the browser immediately. Then the interactive runtime (Server/WebAssembly) loads and re-renders the component with full interactivity.

This means:

  • OnInitializedAsync runs twice — once during prerender (static), once when the interactive runtime attaches.
  • OnAfterRenderAsync is NOT called during prerender — only after the interactive render.
  • Internal navigation between interactive pages (interactive routing) skips prerendering — prerendering only happens on full page loads.

Step 1 — Read the Project's AGENTS.md

Check the project's AGENTS.md for the Interactivity Mode and Interactivity Scope:

Mode Prerendering applies?
None (Static SSR) No — there's no interactive handoff
Server Yes
WebAssembly Yes
Auto Yes

If the mode is None, this skill doesn't apply.

Persist State Across Prerender → Interactive

The most common prerendering problem: data loaded in OnInitializedAsync during prerender is thrown away and re-fetched when the interactive runtime attaches. This causes flicker and duplicate API/DB calls.

Recommended: [PersistentState] attribute

Annotate properties to automatically serialize during prerender and restore on interactive activation:

@page "/forecasts"
@rendermode InteractiveServer

<h1>Weather</h1>

@if (Forecasts is null)
{
    <p>Loading...</p>
}
else
{
    @foreach (var f in Forecasts)
    {
        <p>@f.Date: @f.TemperatureC°C</p>
    }
}

@code {
    [PersistentState]
    public WeatherForecast[]? Forecasts { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Forecasts ??= await ForecastService.GetForecastsAsync();
    }
}

The ??= pattern is critical — it means "only fetch if the property wasn't already restored from prerender state."

Multiple instances of the same component

When the same component type appears multiple times, use @key to disambiguate state:

@foreach (var item in items)
{
    <ItemCard @key="item.Id" />
}

Advanced: PersistentComponentState service

For complex scenarios (dynamic keys, custom serialization), use the imperative API:

@inject PersistentComponentState ApplicationState

@code {
    private List<Order>? orders;

    protected override async Task OnInitializedAsync()
    {
        ApplicationState.RegisterOnPersisting(PersistOrders);

        if (!ApplicationState.TryTakeFromJson<List<Order>>("orders", out var restored))
        {
            orders = await OrderService.GetOrdersAsync();
        }
        else
        {
            orders = restored;
        }
    }

    private Task PersistOrders()
    {
        ApplicationState.PersistAsJson("orders", orders);
        return Task.CompletedTask;
    }
}

Disable Prerendering

Disable prerendering when a component depends on browser APIs immediately or when the prerender+interactive double render causes problems you can't solve with [PersistentState].

On a component definition

@rendermode @(new InteractiveServerRenderMode(prerender: false))

Replace InteractiveServerRenderMode with InteractiveWebAssemblyRenderMode or InteractiveAutoRenderMode as needed.

On a component instance

<MyChart @rendermode="new InteractiveServerRenderMode(prerender: false)" />

On the entire app

In App.razor:

<HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
<Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />

Note: A parent's prerendering setting overrides children. If <Routes> disables prerendering, individual pages cannot re-enable it.

Exclude Pages from Interactive Routing

In a globally interactive app, some pages may need HttpContext (cookies, request headers, response status codes). These pages must render via static SSR, not inside the interactive runtime.

Use [ExcludeFromInteractiveRouting]:

@page "/privacy"
@attribute [ExcludeFromInteractiveRouting]

<h1>Privacy Policy</h1>

This forces a full page reload when navigating to this page, exiting interactive routing. The page renders as static SSR with full HttpContext access.

In App.razor, conditionally apply the render mode:

<!DOCTYPE html>
<html>
<head>
    <HeadOutlet @rendermode="RenderModeForPage" />
</head>
<body>
    <Routes @rendermode="RenderModeForPage" />
    <script src="_framework/blazor.web.js"></script>
</body>
</html>

@code {
    [CascadingParameter]
    public HttpContext HttpContext { get; set; } = default!;

    private IComponentRenderMode? RenderModeForPage =>
        HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null;
}

Replace InteractiveServer with the app's configured render mode.

Detect Prerender vs Interactive at Runtime

Use RendererInfo to guard code that should only run interactively:

protected override async Task OnInitializedAsync()
{
    if (RendererInfo.IsInteractive)
    {
        // Only runs during the interactive render, not during prerender
        await StartSignalRConnection();
    }
}

RendererInfo properties:

  • IsInteractivefalse during prerender, true after interactive runtime attaches
  • Name"Static" during prerender, "Server" or "WebAssembly" when interactive

Client Services Fail During Prerender

Components in the .Client project prerender on the server. Services registered only in the client Program.cs (e.g., IWebAssemblyHostEnvironment) won't be available during prerender.

Fix by one of:

  1. Register a matching service on the server — both Program.cs files provide the service
  2. Make the service optional — use constructor injection with a nullable default: public MyComponent(IMyService? svc = null)
  3. Create a service abstraction — interface in .Client, implementations in both projects
  4. Disable prerendering for that component

Don'ts

  • Don't call JS interop in OnInitializedAsync — JS isn't available during prerender. Use OnAfterRenderAsync(firstRender).
  • Don't assume OnInitializedAsync runs once — it runs twice with prerendering. Always use [PersistentState] or ??= guards.
  • Don't use HttpContext in interactive components — it's only available during the static prerender, not during the interactive lifetime. Use [ExcludeFromInteractiveRouting] for pages that need it.
  • Don't disable prerendering as a first resort — it hurts perceived load time and SEO. Use [PersistentState] to preserve state instead.

Version History

  • ce75c35 Current 2026-07-06 00:30

Same Skill Collection

.agents/skills/create-custom-agent/SKILL.md
.agents/skills/create-skill-test/SKILL.md
.agents/skills/create-skill/SKILL.md
.agents/skills/improve-skill-quality/SKILL.md
.github/skills/agentic-workflows/SKILL.md
eng/skill-validator/tests/fixtures/sample-skill/SKILL.md
plugins/dotnet-advanced/skills/csharp-scripts/SKILL.md
plugins/dotnet-advanced/skills/nuget-trusted-publishing/SKILL.md
plugins/dotnet-aspnetcore/skills/configuring-opentelemetry-dotnet/SKILL.md
plugins/dotnet-aspnetcore/skills/dotnet-webapi/SKILL.md
plugins/dotnet-aspnetcore/skills/minimal-api-file-upload/SKILL.md
plugins/dotnet-blazor/skills/create-blazor-project/SKILL.md
plugins/dotnet-blazor/skills/fetch-and-send-data/SKILL.md
plugins/dotnet-blazor/skills/use-js-interop/SKILL.md
plugins/dotnet-data/skills/optimizing-ef-core-queries/SKILL.md
plugins/dotnet-diag/skills/analyzing-dotnet-performance/SKILL.md
plugins/dotnet-diag/skills/clr-activation-debugging/SKILL.md
plugins/dotnet-diag/skills/dotnet-trace-collect/SKILL.md
plugins/dotnet-diag/skills/dump-collect/SKILL.md
plugins/dotnet-experimental/skills/exp-mock-usage-analysis/SKILL.md
plugins/dotnet-experimental/skills/exp-simd-vectorization/SKILL.md
plugins/dotnet-msbuild/skills/binlog-failure-analysis/SKILL.md
plugins/dotnet-msbuild/skills/copy-to-output-directory/SKILL.md
plugins/dotnet-msbuild/skills/msbuild-server/SKILL.md
plugins/dotnet-msbuild/skills/resolve-project-references/SKILL.md
plugins/dotnet-test-migration/skills/migrate-xunit-to-mstest/SKILL.md
plugins/dotnet-test-migration/skills/migrate-xunit-to-xunit-v3/SKILL.md
plugins/dotnet-test/skills/code-testing-extensions/SKILL.md
plugins/dotnet-test/skills/filter-syntax/SKILL.md
plugins/dotnet-test/skills/find-untested-sources/SKILL.md
plugins/dotnet-test/skills/platform-detection/SKILL.md
plugins/dotnet-upgrade/skills/dotnet-aot-compat/SKILL.md
.agents/skills/authoring-github-workflows/SKILL.md
plugins/dotnet-advanced/skills/dotnet-pinvoke/SKILL.md
plugins/dotnet-ai/skills/mcp-csharp-create/SKILL.md
plugins/dotnet-ai/skills/mcp-csharp-debug/SKILL.md
plugins/dotnet-ai/skills/mcp-csharp-test/SKILL.md
plugins/dotnet-ai/skills/technology-selection/SKILL.md
plugins/dotnet-aspnetcore/skills/convert-blazor-server-to-webapp/SKILL.md
plugins/dotnet-blazor/skills/author-component/SKILL.md
plugins/dotnet-blazor/skills/collect-user-input/SKILL.md
plugins/dotnet-blazor/skills/configure-auth/SKILL.md
plugins/dotnet-blazor/skills/coordinate-components/SKILL.md
plugins/dotnet-blazor/skills/plan-ui-change/SKILL.md
plugins/dotnet-data/skills/create-datadriven-aspnetcore/SKILL.md
plugins/dotnet-diag/skills/android-tombstone-symbolication/SKILL.md
plugins/dotnet-diag/skills/apple-crash-symbolication/SKILL.md
plugins/dotnet-diag/skills/microbenchmarking/SKILL.md
plugins/dotnet-experimental/skills/exp-test-maintainability/SKILL.md

Metadata

Files
0
Version
2124a6e
Hash
ba0f2ed0
Indexed
2026-07-06 00:30

Главная - Вики-сайт
Copyright © 2011-2026 iteam. Current version is 2.155.2. UTC+08:00, 2026-08-04 02:35
浙ICP备14020137号-1 $Гость$