在 Blazor WebAssembly 中包含 appsettings.override.json 文件时遇到困难

问题描述 投票:0回答:1
Blazor 客户端的

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();

我在浏览器控制台中遇到以下错误。

enter image description here

在 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 blazor-webassembly appsettings
1个回答
0
投票

由于 Blazor WebAssembly 运行在浏览器中,因此无法直接访问文件系统,但文件必须位于

wwwroot
目录中。所以正确的处理方法是将
appsettings.override.json
放入
wwwroot
文件夹中,通过HTTP请求加载。可以参考这个例子:

我在wwwroot文件夹中创建了

appsettings.override.json
enter image description here

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++;
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.