Blazor Server 依赖 ASPNETCORE_ENVIRONMENT 环境变量自动加载对应 appsettings.{Environment}.json 并覆盖基础配置;Blazor WebAssembly 则在构建时由 MSBuild 的 EnvironmentName 属性决定打包哪个配置文件并重命名为 appsettings.json。
Blazor 应用(尤其是 Blazor Server 和 Blazor WebAssembly 从 .NET 6+ 开始)支持通过 appsettings.json 实现环境感知的配置,但具体机制因托管模型不同而有差异。核心原则是:**环境变量决定加载哪个配置文件,而非手动切换文件名**。
Blazor Server 本质是服务端渲染,直接复用 ASP.NET Core 的配置系统,支持多环境配置文件自动合并:
appsettings.json(所有环境共享)appsettings.Development.json、appsettings.Production.json 等ASPNETCORE_ENVIRONMENT 环境变量值(如 Development)自动加载对应文件,且环境文件会覆盖基础文件中同名配置项Program.cs 中通过 builder.Configuration 注入,例如 builder.Services.Configure(builder.Configuration.GetSection("MySettings"))
WebAssembly 运行在浏览器中,无法读取服务器环境变量,因此配置加载是显式、静态的:
appsettings.json(开发时)和 appsettings.{Environment}.json(发布后) MSBuild 属性(如 Production)自动复制对应文件(如 appsettings.Production.json)并重命名为 appsettings.json,覆盖默认文件index.html 的 标签中添加 autostart="false",然后调用 Blazor.start() 并传入 {
environment: 'Staging' } —— 但这仅影响 Blazor 自身日志级别等内部行为,不触发配置文件切换
Staging ,或使用 dotnet publish -c Release -p:EnvironmentName=Staging
无论哪种 Blazor 模型,都推荐将配置抽象为 C# 类,提高可维护性与类型安全:
public class ApiSettings { public string BaseUrl { get; set; } }
appsettings.json 中写入对应结构:"ApiSettings": { "BaseUrl": "https://api.example.com" }
builder.Services.Configure(builder.Configuration.GetSection("ApiSettings"))
IOptions 或 IOptionsSnapshot 使用快速验证配置是否按预期加载:
Program.cs 中临时加 Console.WriteLine(builder.Configuration["MyKey"]);
Program.cs 的 builder.Services.Add...() 前,用 await builder.Configuration.ReloadAsync(); 确保已加载完成,再打印 builder.Configuration.AsEnumerable() 查看全部键值对
appsettings.json 还是 appsettings.Production.json
基本上就这些。关键区别在于:Server 看环境变量自动选,WASM 看构建时指定的 EnvironmentName 静态打包。不复杂但容易忽略细节。