Blazor WASM(WebAssembly)和Blazor服务器端都是ASP.NET Core的一部分,但它们是不同的解决方案。
Blazor WASM是一种使用WebAssembly技术在客户端运行的单页应用程序(SPA)。它可以在浏览器中直接运行,无需服务器参与。它使用C#语言和.NET运行时在客户端执行逻辑。示例代码如下:
// Program.cs
using BlazorWasmApp;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using System;
using System.Threading.Tasks;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("#app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
Blazor服务器端是一种在服务器上运行的应用程序模型。它使用SignalR实时通信技术将用户界面呈现在浏览器中,并将用户输入发送到服务器进行处理。示例代码如下:
// Program.cs
using BlazorServerApp.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
因此,Blazor WASM和Blazor服务器端是不同的解决方案,其设计和用法也有所不同。您可以根据您的需求选择适合的解决方案。