使用 ASP.NET Core 6.0 Blazor 配置。默认情况下,Blazor WebAssembly 从以下应用程序设置文件加载配置:
- wwwroot/appsettings.json。
- wwwroot/appsettings.{ENVIRONMENT}.json,其中 {ENVIRONMENT}
占位符是应用程序的运行环境 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-6.0.
Example:
wwwroot/appsettings.json
{
"h1FontSize": "50px"
}
页面/ConfigurationExample.razor
@page "/configuration-example"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<h1 style="font-size:@Configuration["h1FontSize"]">
Configuration example
</h1>
警告 Blazor WebAssembly 应用程序中的配置和设置文件
对用户可见。不存储应用程序机密、凭据或任何
Blazor 配置或文件中的其他敏感数据
WebAssembly 应用程序。
https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0 https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0
您还可以将值绑定到类。
public class ClientAppSettings
{
public string h1FontSize{ get; set; }
}
然后将此类作为 Singleton 添加到 Program.cs 中:
var settings = new ClientAppSettings();
builder.Configuration.Bind(settings);
builder.Services.AddSingleton(settings);
添加命名空间到_Imports.razor
然后在需要的地方注入以在 Visual Studio 中使用自动完成功能获取设置:
@inject ClientAppSettings ClientAppSettings