blazor-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Blazor Expert - Orchestration Hub

Blazor专家 - 编排中心

Expert-level guidance for developing applications with Blazor, Microsoft's framework for building interactive web UIs using C# instead of JavaScript.
针对使用Blazor开发应用的专家级指导,Blazor是微软推出的使用C#而非JavaScript构建交互式Web UI的框架。

Quick Reference: When to Load Which Resource

快速参考:何时加载对应资源

TaskLoad ResourceKey Topics
Build components, handle lifecycle eventscomponents-lifecycle.mdComponent structure, lifecycle methods, parameters, cascading values, RenderFragment composition
Manage component state, handle eventsstate-management-events.mdLocal state, EventCallback, data binding, cascading state, service-based state
Configure routes, navigate between pagesrouting-navigation.mdRoute parameters, constraints, navigation, NavLink, query strings, layouts
Build forms, validate user inputforms-validation.mdEditForm, input components, DataAnnotations validation, custom validators
Setup authentication & authorizationauthentication-authorization.mdAuth setup, AuthorizeView, Authorize attribute, policies, claims
Optimize performance, use JavaScript interopperformance-advanced.mdRendering optimization, virtualization, JS interop, lazy loading, WASM best practices
任务加载资源核心主题
构建组件、处理生命周期事件components-lifecycle.md组件结构、生命周期方法、参数、级联值、RenderFragment组合
管理组件状态、处理事件state-management-events.md本地状态、EventCallback、数据绑定、级联状态、基于服务的状态
配置路由、页面间导航routing-navigation.md路由参数、约束、导航、NavLink、查询字符串、布局
构建表单、验证用户输入forms-validation.mdEditForm、输入组件、DataAnnotations验证、自定义验证器
设置身份验证与授权authentication-authorization.md身份验证设置、AuthorizeView、Authorize特性、策略、声明
优化性能、使用JavaScript互操作performance-advanced.md渲染优化、虚拟化、JS互操作、懒加载、WASM最佳实践

Orchestration Protocol

编排协议

Phase 1: Task Analysis

阶段1:任务分析

Identify your primary objective:
  • UI Building → Load components-lifecycle.md
  • State Handling → Load state-management-events.md
  • Navigation → Load routing-navigation.md
  • Data Input → Load forms-validation.md
  • User Access → Load authentication-authorization.md
  • Speed/Efficiency → Load performance-advanced.md
确定你的主要目标:
  • UI构建 → 加载components-lifecycle.md
  • 状态处理 → 加载state-management-events.md
  • 导航 → 加载routing-navigation.md
  • 数据输入 → 加载forms-validation.md
  • 用户访问控制 → 加载authentication-authorization.md
  • 速度/效率优化 → 加载performance-advanced.md

Phase 2: Resource Loading

阶段2:资源加载

Open the recommended resource file(s) and search for your specific need using Ctrl+F. Each resource is organized by topic with working code examples.
打开推荐的资源文件,使用Ctrl+F搜索你的特定需求。每个资源都按主题组织,并包含可运行的代码示例。

Phase 3: Implementation & Validation

阶段3:实现与验证

  • Follow code patterns from the resource
  • Adapt to your specific requirements
  • Test in appropriate hosting model (Server/WASM/Hybrid)
  • Review troubleshooting section if issues arise
  • 遵循资源中的代码模式
  • 根据你的特定需求进行调整
  • 在合适的托管模型(Server/WASM/Hybrid)中测试
  • 若出现问题,查阅故障排除部分

Blazor Hosting Models Overview

Blazor托管模型概述

Blazor Server

Blazor Server

  • How: Runs on server via SignalR
  • Best For: Line-of-business apps, need full .NET runtime, small download size
  • Trade-offs: High latency, requires connection, server resource intensive
  • 工作方式:通过SignalR在服务器上运行
  • 最佳适用场景:企业级应用、需要完整.NET运行时、下载包体积小的场景
  • 权衡点:延迟较高、需要持续连接、占用服务器资源多

Blazor WebAssembly

Blazor WebAssembly

  • How: Runs in browser via WebAssembly
  • Best For: PWAs, offline apps, no server dependency, client-heavy applications
  • Trade-offs: Large initial download, limited .NET APIs, slower cold start
  • 工作方式:通过WebAssembly在浏览器中运行
  • 最佳适用场景:渐进式Web应用(PWA)、离线应用、无服务器依赖、客户端负载重的应用
  • 权衡点:初始下载包体积大、支持的.NET API有限、冷启动速度慢

Blazor Hybrid

Blazor Hybrid

  • How: Runs in MAUI/WPF/WinForms with Blazor UI
  • Best For: Cross-platform desktop/mobile apps
  • Trade-offs: Platform-specific considerations, additional dependencies
Decision: Choose based on deployment environment, offline requirements, and server constraints.
  • 工作方式:在MAUI/WPF/WinForms中运行Blazor UI
  • 最佳适用场景:跨平台桌面/移动应用
  • 权衡点:需考虑平台特定因素、额外依赖项
决策建议:根据部署环境、离线需求和服务器限制进行选择。

Common Implementation Workflows

常见实现工作流

Scenario 1: Build a Data-Entry Component

场景1:构建数据录入组件

  1. Read components-lifecycle.md - Component structure section
  2. Read state-management-events.md - EventCallback pattern
  3. Read forms-validation.md - EditForm component
  4. Combine: Create component with parameters → capture user input → validate → notify parent
  1. 阅读components-lifecycle.md - 组件结构章节
  2. 阅读state-management-events.md - EventCallback模式
  3. 阅读forms-validation.md - EditForm组件
  4. 整合:创建带参数的组件 → 捕获用户输入 → 验证 → 通知父组件

Scenario 2: Implement User Authentication & Protected Pages

场景2:实现用户身份验证与受保护页面

  1. Read authentication-authorization.md - Setup section
  2. Read routing-navigation.md - Layouts section
  3. Read authentication-authorization.md - AuthorizeView section
  4. Combine: Configure auth → create login page → protect routes → check auth in components
  1. 阅读authentication-authorization.md - 设置章节
  2. 阅读routing-navigation.md - 布局章节
  3. 阅读authentication-authorization.md - AuthorizeView章节
  4. 整合:配置身份验证 → 创建登录页面 → 保护路由 → 在组件中检查身份验证状态

Scenario 3: Build Interactive List with Search/Filter

场景3:构建带搜索/筛选的交互式列表

  1. Read routing-navigation.md - Query strings section
  2. Read state-management-events.md - Data binding section
  3. Read performance-advanced.md - Virtualization section
  4. Combine: Capture search input → update URL query → fetch filtered data → virtualize if large
  1. 阅读routing-navigation.md - 查询字符串章节
  2. 阅读state-management-events.md - 数据绑定章节
  3. 阅读performance-advanced.md - 虚拟化章节
  4. 整合:捕获搜索输入 → 更新URL查询参数 → 获取筛选后的数据 → 若数据量大则使用虚拟化

Scenario 4: Optimize Performance of Existing App

场景4:优化现有应用的性能

  1. Read performance-advanced.md - All sections
  2. Identify bottlenecks:
    • Unnecessary renders? → ShouldRender override, @key directive
    • Large lists? → Virtualization
    • JS latency? → Module isolation pattern
  3. Apply targeted optimizations from resource
  1. 阅读performance-advanced.md - 所有章节
  2. 识别性能瓶颈:
    • 不必要的渲染?→ 重写ShouldRender、使用@key指令
    • 大型列表?→ 虚拟化
    • JS交互延迟?→ 模块隔离模式
  3. 应用资源中的针对性优化方案

Key Blazor Concepts

Blazor核心概念

Component Architecture

组件架构

  • Components: Self-contained UI units with optional logic
  • Parameters: Inputs to components, enable reusability
  • Cascading Values: Share state with descendants without explicit parameters
  • Events: Child-to-parent communication via EventCallback
  • Layouts: Parent wrapper for consistent page structure
  • 组件:独立的UI单元,可包含可选逻辑
  • 参数:组件的输入,提升可复用性
  • 级联值:无需显式参数即可与子组件共享状态
  • 事件:通过EventCallback实现子组件到父组件的通信
  • 布局:为页面提供一致结构的父级包装器

State Management

状态管理

  • Local State: Component-specific fields and properties
  • Cascading Values: Share state to descendants
  • Services: Application-wide state via dependency injection
  • Event Binding: React to user interactions
  • Data Binding: Two-way synchronization with UI
  • 本地状态:组件特定的字段和属性
  • 级联值:向子组件共享状态
  • 服务:通过依赖注入实现应用级状态共享
  • 事件绑定:响应用户交互
  • 数据绑定:与UI进行双向同步

Routing & Navigation

路由与导航

  • @page Directive: Make component routable
  • Route Parameters: Pass data via URL (
    {id:int}
    )
  • Navigation: Programmatic navigation via NavigationManager
  • NavLink: UI component that highlights active route
  • Layouts: Wrap pages with common structure
  • @page指令:使组件可路由
  • 路由参数:通过URL传递数据(如
    {id:int}
  • 导航:通过NavigationManager实现程序化导航
  • NavLink:可高亮当前激活路由的UI组件
  • 布局:用通用结构包装页面

Forms & Validation

表单与验证

  • EditForm: Form component with validation support
  • Input Components: Typed controls (InputText, InputNumber, etc.)
  • Validators: DataAnnotations attributes or custom logic
  • EventCallback: Notify parent of form changes
  • Messages: Display validation errors to user
  • EditForm:支持验证的表单组件
  • 输入组件:类型化控件(InputText、InputNumber等)
  • 验证器:DataAnnotations特性或自定义逻辑
  • EventCallback:通知父组件表单变更
  • 消息提示:向用户显示验证错误

Authentication & Authorization

身份验证与授权

  • Claims & Roles: Identify users and define access levels
  • Policies: Fine-grained authorization rules
  • Authorize Attribute: Protect pages from unauthorized access
  • AuthorizeView: Conditional rendering based on permissions
  • AuthenticationStateProvider: Get current user information
  • 声明与角色:识别用户并定义访问级别
  • 策略:细粒度的授权规则
  • Authorize特性:保护页面免受未授权访问
  • AuthorizeView:根据权限条件渲染内容
  • AuthenticationStateProvider:获取当前用户信息

Performance Optimization

性能优化

  • ShouldRender(): Prevent unnecessary re-renders
  • @key Directive: Help diffing algorithm match list items
  • Virtualization: Render only visible items in large lists
  • JS Interop: Call JavaScript from C# and vice versa
  • AOT/Trimming: Reduce WASM download size (production)
  • ShouldRender():防止不必要的渲染
  • @key指令:帮助差异算法匹配列表项
  • 虚拟化:仅渲染大型列表中的可见项
  • JS互操作:从C#调用JavaScript,反之亦然
  • AOT/裁剪:减小WASM下载包体积(生产环境)

Best Practices Highlights

最佳实践要点

Component Design

组件设计

Single Responsibility - Each component has one clear purpose ✅ Composition - Use RenderFragments for flexible layouts ✅ Parameter Clarity - Use descriptive names, mark required with
[EditorRequired]
Proper Disposal - Implement
IDisposable
to clean up resources ✅ Event-Based Communication - Use
EventCallback
for child-to-parent updates
单一职责 - 每个组件有明确的单一用途 ✅ 组合模式 - 使用RenderFragments实现灵活布局 ✅ 参数清晰 - 使用描述性名称,用
[EditorRequired]
标记必填参数 ✅ 正确释放资源 - 实现
IDisposable
清理资源 ✅ 基于事件的通信 - 使用
EventCallback
实现子到父的更新

State Management

状态管理

EventCallback Over Action - Proper async handling ✅ Immutable Updates - Create new objects/collections, don't mutate ✅ Service-Based State - Use scoped services for shared state ✅ Unsubscribe from Events - Prevent memory leaks in Dispose ✅ InvokeAsync for Background Threads - Thread-safe state updates
优先使用EventCallback而非Action - 支持正确的异步处理 ✅ 不可变更新 - 创建新对象/集合,而非修改原有对象 ✅ 基于服务的状态 - 使用作用域服务实现共享状态 ✅ 取消事件订阅 - 在Dispose中防止内存泄漏 ✅ 后台线程使用InvokeAsync - 线程安全的状态更新

Routing & Navigation

路由与导航

Route Constraints - Use
:int
,
:guid
, etc. to validate formats ✅ NavLink Component - Automatic active state highlighting ✅ forceLoad After Logout - Clear client-side state ✅ ReturnUrl Pattern - Redirect back after login ✅ Query Strings - Preserve filters/pagination across navigation
路由约束 - 使用
:int
:guid
等验证格式 ✅ NavLink组件 - 自动高亮当前激活路由 ✅ 登出后强制加载 - 清理客户端状态 ✅ ReturnUrl模式 - 登录后重定向回原页面 ✅ 查询字符串 - 在导航时保留筛选/分页信息

Forms & Validation

表单与验证

EditForm + DataAnnotationsValidator - Built-in validation ✅ ValidationMessage - Show field-level errors ✅ Custom Validators - Extend for complex rules ✅ Async Validation - Check server availability before submit ✅ Loading State - Disable submit button while processing
EditForm + DataAnnotationsValidator - 内置验证方案 ✅ ValidationMessage - 显示字段级错误 ✅ 自定义验证器 - 扩展以支持复杂规则 ✅ 异步验证 - 提交前检查服务器可用性 ✅ 加载状态 - 处理过程中禁用提交按钮

Authentication & Authorization

身份验证与授权

Server Validation - Never trust client-side checks alone ✅ Policies Over Roles - More flexible authorization rules ✅ Claims for Details - Store user attributes in claims ✅ Cascading AuthenticationState - Available in all components ✅ Error Boundaries - Graceful error handling
服务器端验证 - 绝不单独信任客户端检查 ✅ 优先使用策略而非角色 - 更灵活的授权规则 ✅ 使用声明存储详情 - 在声明中存储用户属性 ✅ 级联AuthenticationState - 所有组件均可访问 ✅ 错误边界 - 优雅处理错误

Performance

性能

@key on Lists - Optimize item matching ✅ ShouldRender Override - Prevent unnecessary renders ✅ Virtualization for Large Lists - Only render visible items ✅ JS Module Isolation - Load and cache JS modules efficiently ✅ AOT for WASM - Production deployments
列表使用@key - 优化项匹配 ✅ 重写ShouldRender - 防止不必要的渲染 ✅ 大型列表使用虚拟化 - 仅渲染可见项 ✅ JS模块隔离 - 高效加载和缓存JS模块 ✅ WASM使用AOT - 生产环境部署

Common Troubleshooting

常见故障排除

Component Not Re-rendering

组件未重新渲染

  • Cause: Mutation instead of reassignment
  • Fix: Create new object/collection:
    items = items.Append(item).ToList()
  • Or: Call
    StateHasChanged()
    manually
  • 原因:修改对象而非重新赋值
  • 解决方法:创建新对象/集合:
    items = items.Append(item).ToList()
  • :手动调用
    StateHasChanged()

Parameter Not Updating

参数未更新

  • Cause: Parent not re-rendering or same object reference
  • Fix: Parent must re-render, ensure new reference for objects
  • Debug: Check OnParametersSet is firing
  • 原因:父组件未重新渲染或引用了相同对象
  • 解决方法:父组件必须重新渲染,确保对象使用新引用
  • 调试:检查OnParametersSet是否触发

JS Interop Errors

JS互操作错误

  • Cause: Called before script loaded or wrong function name
  • Fix: Use
    firstRender
    check, verify JS file path
  • Pattern: Use module isolation:
    await JS.InvokeAsync("import", "./script.js")
  • 原因:脚本加载前调用或函数名称错误
  • 解决方法:使用
    firstRender
    检查,验证JS文件路径
  • 推荐模式:使用模块隔离:
    await JS.InvokeAsync("import", "./script.js")

Authentication State Not Available

身份验证状态不可用

  • Cause: Cascading parameter not provided or timing issue
  • Fix: Ensure AuthenticationStateProvider configured
  • Pattern: Always null-check and use
    await AuthStateTask!
    in code block
  • 原因:未提供级联参数或时序问题
  • 解决方法:确保已配置AuthenticationStateProvider
  • 推荐模式:始终进行空检查,并在代码块中使用
    await AuthStateTask!

Large List Performance Issues

大型列表性能问题

  • Cause: Rendering all items in DOM
  • Fix: Use Virtualize component for 1000+ items
  • Alternative: Paginate with buttons/infinite scroll
  • 原因:在DOM中渲染所有项
  • 解决方法:对1000+项使用Virtualize组件
  • 替代方案:使用按钮分页或无限滚动

Blazor Server Connection Issues

Blazor Server连接问题

  • Cause: SignalR connection dropped or configuration issue
  • Fix: Implement reconnection UI, increase timeout
  • Config: Adjust
    CircuitOptions.DisconnectedCircuitRetentionPeriod
  • 原因:SignalR连接断开或配置问题
  • 解决方法:实现重连UI,增加超时时间
  • 配置调整:修改
    CircuitOptions.DisconnectedCircuitRetentionPeriod

Resource Files Summary

资源文件摘要

components-lifecycle.md

components-lifecycle.md

Complete guide to component structure, lifecycle methods, parameters, cascading values, and composition patterns. Essential for understanding Blazor component fundamentals.
组件结构、生命周期方法、参数、级联值和组合模式的完整指南。是理解Blazor组件基础的必备内容。

state-management-events.md

state-management-events.md

Comprehensive coverage of local and service-based state, event handling with EventCallback, data binding patterns, and component communication. Core for interactive UI building.
全面覆盖本地和基于服务的状态、使用EventCallback的事件处理、数据绑定模式以及组件通信。是构建交互式UI的核心内容。

routing-navigation.md

routing-navigation.md

Complete routing reference including route parameters, constraints, programmatic navigation, query strings, and layout management. Essential for multi-page apps.
完整的路由参考,包括路由参数、约束、程序化导航、查询字符串和布局管理。是多页面应用的必备内容。

forms-validation.md

forms-validation.md

Full forms API with EditForm component, input controls, DataAnnotations validation, custom validators, and form patterns. Required for data entry scenarios.
完整的表单API,包含EditForm组件、输入控件、DataAnnotations验证、自定义验证器和表单模式。是数据录入场景的必备内容。

authentication-authorization.md

authentication-authorization.md

Complete auth setup for Server and WASM, AuthorizeView, policies, claims-based access control, and login/logout patterns. Necessary for secured applications.
针对Server和WASM的完整身份验证设置、AuthorizeView、策略、基于声明的访问控制以及登录/登出模式。是构建安全应用的必备内容。

performance-advanced.md

performance-advanced.md

Performance optimization techniques including ShouldRender, virtualization, JavaScript interop patterns, lazy loading, and WASM best practices. Vital for production apps.

性能优化技术,包括ShouldRender、虚拟化、JavaScript互操作模式、懒加载和WASM最佳实践。是生产环境应用的必备内容。

Implementation Approach

实现方法

When implementing Blazor features:
  1. Identify Your Task - Match against the decision table above
  2. Load Relevant Resource - Read the appropriate .md file
  3. Find Code Example - Search resource for similar implementation
  4. Adapt to Your Context - Modify for your specific requirements
  5. Test Thoroughly - Verify in your hosting model
  6. Reference Troubleshooting - Consult resource if issues arise
在实现Blazor功能时:
  1. 确定任务 - 与上方的决策表匹配
  2. 加载相关资源 - 阅读对应的.md文件
  3. 查找代码示例 - 在资源中搜索类似实现
  4. 适配你的场景 - 根据特定需求修改
  5. 全面测试 - 在你的托管模型中验证
  6. 查阅故障排除 - 若出现问题,参考资源中的相关部分

Next Steps

下一步建议

  • New to Blazor? Start with components-lifecycle.md
  • Building Data App? Move through: components → state → forms → validation
  • Scaling Existing App? Focus on performance-advanced.md
  • Adding Security? Follow authentication-authorization.md

Version: 2.0 - Modular Orchestration Pattern
Last Updated: December 4, 2025
Status: Production Ready ✅
  • Blazor新手?components-lifecycle.md开始
  • 构建数据应用? 按以下顺序学习:组件 → 状态 → 表单 → 验证
  • 扩展现有的应用? 重点关注performance-advanced.md
  • 添加安全功能? 遵循authentication-authorization.md

版本:2.0 - 模块化编排模式
最后更新:2025年12月4日
状态:已就绪可用于生产环境 ✅",