在 C# 中实现 Blazor 应用需要结合 Razor 语法和 C# 代码,Blazor 允许使用 C# 同时开发前端和后端逻辑。以下是一个完整的 C# Blazor 实现示例,包含项目创建、基础组件和数据交互等内容:
一、创建 Blazor 项目
使用 Visual Studio
- 新建项目 → 选择 “Blazor App” → 勾选 “ASP.NET Core 托管”(可选 WebAssembly 或服务器端渲染)。
使用.NET CLI
dotnet new blazorwasm -n BlazorDemo # WebAssembly客户端渲染 dotnet new blazorserver -n BlazorDemo # 服务器端渲染
二、基础 Blazor 组件示例(C#)
以下是一个显示当前时间的 Blazor 组件(.razor
文件):
@page "/" // 路由路径
<h3>Blazor时间组件</h3>
<p>当前时间:@currentTime</p>
<button @onclick="UpdateTime">刷新时间</button>
@code {
private string currentTime;
protected override void OnInitialized()
{
UpdateTime();
}
private void UpdateTime()
{
currentTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
StateHasChanged(); // 通知组件状态更新
}
}
三、数据绑定与交互
Blazor 支持双向数据绑定和事件处理:razor
@page "/form"
<h3>用户表单</h3>
<div>
<label>姓名:</label>
<input type="text" @bind="userName" />
<p>输入的姓名:@userName</p>
</div>
<div>
<label>年龄:</label>
<input type="number" @bind="userAge" />
<p>年龄:@userAge</p>
</div>
<button @onclick="SubmitForm">提交</button>
@code {
private string userName;
private int userAge;
private void SubmitForm()
{
if (string.IsNullOrEmpty(userName))
{
message = "姓名不能为空";
return;
}
message = $"用户 {userName},年龄 {userAge} 已提交";
}
private string message;
}
四、组件间通信(父子组件)
父组件(ParentComponent.razor)razor
<h3>父组件</h3>
<p>父组件消息:@parentMessage</p>
<ChildComponent @bind-ChildMessage="parentMessage" />
@code {
private string parentMessage = "来自父组件的初始消息";
}
子组件(ChildComponent.razor)razor
<h4>子组件</h4>
<input type="text" @bind="childMessage" />
<p>子组件接收到的消息:@childMessage</p>
@code {
[Parameter]
public string ChildMessage {
get => childMessage;
set {
if (childMessage != value)
{
childMessage = value;
OnChildMessageChanged.InvokeAsync(childMessage);
}
}
}
private string childMessage;
[Parameter]
public EventCallback<string> OnChildMessageChanged { get; set; }
}
五、HTTP 数据交互
Blazor 内置HttpClient
用于 API 调用:
@page "/fetch-data"
@using System.Net.Http
@using BlazorDemo.Shared // 假设模型在此命名空间
<h3>获取天气数据</h3>
@if (forecasts == null)
{
<p><em>加载中...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>日期</th>
<th>温度</th>
<th>摘要</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date</td>
<td>@forecast.TemperatureC °C</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@code {
private WeatherForecast[] forecasts;
// 注入HttpClient
[Inject]
private HttpClient Http { get; set; }
protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
}
// 天气模型(通常放在Shared项目中)
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
}
六、Blazor 项目结构说明
plaintext
BlazorDemo/
├── Client/ # WebAssembly客户端项目(若选择ASP.NET Core托管)
├── Server/ # 服务器端项目(包含API和服务)
├── Shared/ # 共享模型和接口
├── wwwroot/ # 静态资源
├── App.razor # 根组件
├── MainLayout.razor # 布局组件
├── _Imports.razor # 全局导入
├── index.html # WebAssembly入口
└── Program.cs # 应用程序入口
七、运行与部署
开发环境运行
dotnet run # 服务器端渲染 dotnet watch run # 启用热重载
部署到 IIS / 云服务
- 发布项目:
dotnet publish -c Release
- WebAssembly 应用可直接部署静态文件;服务器端应用需部署到支持.NET 的服务器(如 Azure App Service)。
- 发布项目:
核心特性总结
- 组件化开发:通过
.razor
文件混合 HTML、C# 和 CSS,实现可复用 UI 组件。 - 双向绑定:使用
@bind
语法简化表单交互(如@bind="userName"
)。 - 依赖注入:通过
[Inject]
特性注入服务(如HttpClient
、数据库上下文)。 - 状态管理:使用
StateHasChanged()
通知组件更新 UI。 - 跨平台:WebAssembly 版可在浏览器中运行,服务器版可部署到任何支持.NET 的平台。
通过以上示例,可快速入门 C# Blazor 开发,进一步可扩展为复杂的企业级应用。
在 Razor 语法中,输出表达式的方式与传统 ASP/ASPX 有所不同。以下是 <%=now%>
在 Razor 中的等效实现方法:
1. 基本语法对比
技术 | 输出当前时间的代码示例 |
---|---|
ASP/ASPX | <%= Now() %> 或 <% Response.Write(Now()) %> |
Razor (VB.NET) | @Now 或 @DateTime.Now |
2. Razor 实现示例
在 .cshtml 文件中
<p>当前时间:@Now</p>
<!-- 等效于 -->
<p>当前时间:@DateTime.Now</p>
<!-- 格式化输出 -->
<p>格式化时间:@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")</p>
在代码块中使用
@Code
Dim currentTime = DateTime.Now
Dim formattedTime = currentTime.ToString("yyyy年MM月dd日")
End Code
<p>代码块中的时间:@formattedTime</p>
3. 动态表达式与 HTML 编码
Razor 会自动对输出内容进行 HTML 编码,防止 XSS 攻击:
@Code
Dim userInput = "<script>alert('XSS');</script>"
End Code
<!-- 输出编码后的内容:<script>alert('XSS');</script> -->
<p>自动编码:@userInput</p>
<!-- 若需输出原始 HTML(需谨慎!) -->
<p>原始 HTML:@Html.Raw(userInput)</p>
4. 与传统 ASPX 的差异
特性 | ASPX (<%= %> ) |
Razor (@ ) |
---|---|---|
语法简洁度 | 较长,需显式标记开始和结束 | 更简洁,使用 @ 符号 |
代码块集成 | 使用 <% %> 包裹代码 |
使用 @Code ... End Code |
HTML 编码 | 需手动调用 Server.HtmlEncode |
自动编码,可通过 @Html.Raw 禁用 |
类型推断 | 弱类型,需显式转换 | 强类型,支持智能感知 |
5. 复杂表达式示例
<!-- 条件表达式 -->
<p>状态:@If(DateTime.Now.Hour < 12, "上午", "下午")</p>
<!-- 方法调用 -->
@Code
Function GetWelcomeMessage() As String
Return "欢迎访问,当前时间:" & DateTime.Now.ToString()
End Function
End Code
<p>消息:@GetWelcomeMessage()</p>
6. 在 Blazor 组件中使用
如果是 Blazor 组件(.razor 文件),语法类似,但支持双向绑定和组件生命周期:
<p>当前时间:@CurrentTime</p>
<button @onclick="UpdateTime">刷新时间</button>
@Code
Private CurrentTime As DateTime = DateTime.Now
Private Sub UpdateTime()
CurrentTime = DateTime.Now
End Sub
End Code