在 C# 中实现 Blazor 应用需要结合 Razor 语法和 C# 代码,Blazor 允许使用 C# 同时开发前端和后端逻辑。以下是一个完整的 C# Blazor 实现示例,包含项目创建、基础组件和数据交互等内容:
使用 Visual Studio
使用.NET CLI
dotnet new blazorwasm -n BlazorDemo # WebAssembly客户端渲染
dotnet new blazorserver -n BlazorDemo # 服务器端渲染
以下是一个显示当前时间的 Blazor 组件(.razor
文件):
@page "/" // 路由路径
Blazor时间组件
当前时间:@currentTime
@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"
用户表单
输入的姓名:@userName
年龄:@userAge
@code {
private string userName;
private int userAge;
private void SubmitForm()
{
if (string.IsNullOrEmpty(userName))
{
message = "姓名不能为空";
return;
}
message = $"用户 {userName},年龄 {userAge} 已提交";
}
private string message;
}
父组件
父组件消息:@parentMessage
@code {
private string parentMessage = "来自父组件的初始消息";
}
子组件
子组件接收到的消息:@childMessage
@code {
[Parameter]
public string ChildMessage {
get => childMessage;
set {
if (childMessage != value)
{
childMessage = value;
OnChildMessageChanged.InvokeAsync(childMessage);
}
}
}
private string childMessage;
[Parameter]
public EventCallback OnChildMessageChanged { get; set; }
}
Blazor 内置HttpClient
用于 API 调用:
@page "/fetch-data"
@using System.Net.Http
@using BlazorDemo.Shared // 假设模型在此命名空间
获取天气数据
@if (forecasts == null)
{
加载中...
}
else
{
日期
温度
摘要
@foreach (var forecast in forecasts)
{
@forecast.Date
@forecast.TemperatureC °C
@forecast.Summary
}
}
@code {
private WeatherForecast[] forecasts;
// 注入HttpClient
[Inject]
private HttpClient Http { get; set; }
protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetFromJsonAsync("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);
}
}
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
.razor
文件混合 HTML、C# 和 CSS,实现可复用 UI 组件。@bind
语法简化表单交互(如@bind="userName"
)。[Inject]
特性注入服务(如HttpClient
、数据库上下文)。StateHasChanged()
通知组件更新 UI。通过以上示例,可快速入门 C# Blazor 开发,进一步可扩展为复杂的企业级应用。
在 Razor 语法中,输出表达式的方式与传统 ASP/ASPX 有所不同。以下是 <%=now%>
在 Razor 中的等效实现方法:
技术 | 输出当前时间的代码示例 |
---|---|
ASP/ASPX | <%= Now() %> 或 <% Response.Write(Now()) %> |
Razor (VB.NET) | @Now 或 @DateTime.Now |
当前时间:@Now
当前时间:@DateTime.Now
格式化时间:@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
@Code
Dim currentTime = DateTime.Now
Dim formattedTime = currentTime.ToString("yyyy年MM月dd日")
End Code
代码块中的时间:@formattedTime
Razor 会自动对输出内容进行 HTML 编码,防止 XSS 攻击:
@Code
Dim userInput = ""
End Code
自动编码:@userInput
原始 HTML:@Html.Raw(userInput)
特性 | ASPX (<%= %> ) |
Razor (@ ) |
---|---|---|
语法简洁度 | 较长,需显式标记开始和结束 | 更简洁,使用 @ 符号 |
代码块集成 | 使用 <% %> 包裹代码 |
使用 @Code ... End Code |
HTML 编码 | 需手动调用 Server.HtmlEncode |
自动编码,可通过 @Html.Raw 禁用 |
类型推断 | 弱类型,需显式转换 | 强类型,支持智能感知 |
状态:@If(DateTime.Now.Hour < 12, "上午", "下午")
@Code
Function GetWelcomeMessage() As String
Return "欢迎访问,当前时间:" & DateTime.Now.ToString()
End Function
End Code
消息:@GetWelcomeMessage()
如果是 Blazor 组件(.razor 文件),语法类似,但支持双向绑定和组件生命周期:
当前时间:@CurrentTime
@Code
Private CurrentTime As DateTime = DateTime.Now
Private Sub UpdateTime()
CurrentTime = DateTime.Now
End Sub
End Code
@
符号提供了更简洁、安全的表达式输出方式,同时支持强类型和智能感知,是 ASP.NET Core 中推荐的视图语法。对于 VB.NET 用户,@Now
是最直接的 <%=Now%>
替代方案。