Program.cs
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Configuration.AddJsonFile("appsettings.override.json", optional: false, reloadOnChange: false);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
await builder.Build().RunAsync();
我在浏览器控制台中遇到以下错误。
在 Blazor WebAssembly 项目中添加自定义 appsettings.override.json 文件的正确方法是什么?
我尝试过:
builder.Configuration.AddJsonFile("appsettings.override.json", optional: false, reloadOnChange: false);
builder.Configuration.AddJsonFile("wwwroot/appsettings.override.json", optional: false, reloadOnChange: false);
由于 Blazor WebAssembly 运行在浏览器中,因此无法直接访问文件系统,但文件必须位于
wwwroot
目录中。所以正确的处理方法是将appsettings.override.json
放入wwwroot
文件夹中,通过HTTP请求加载。可以参考这个例子:
我在wwwroot文件夹中创建了
appsettings.override.json
:
appsettings.override.json:
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"System": "Information",
"Microsoft": "Error"
}
},
"TestSetting": "This is a test setting value from appsettings.override.json",
}
使用HTTP请求加载
program.cs
:
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddSingleton<IConfiguration>(builder.Configuration);
using var httpClient = new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) };
var response = await httpClient.GetAsync("appsettings.override.json");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
var config = new ConfigurationBuilder()
.AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
.Build();
builder.Configuration.AddConfiguration(config);
}
await builder.Build().RunAsync();
在测试页面的配置中显示
TestSetting
:
@page "/counter"
@rendermode InteractiveWebAssembly
@inject IConfiguration Configuration
<h3>test value: @Configuration["TestSetting"]</h3>
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}