Program.cs of Blazor Client
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();
I am encountering the following error in browser console.
What is the correct way to add custom appsettings.override.json file in blazor webassembly project?
I tried:
builder.Configuration.AddJsonFile("appsettings.override.json", optional: false, reloadOnChange: false);
builder.Configuration.AddJsonFile("wwwroot/appsettings.override.json", optional: false, reloadOnChange: false);
Since Blazor WebAssembly runs in the browser, it cannot directly access the file system, but the file must be located in the wwwroot
directory. So the correct way to handle it is to place appsettings.override.json
in the wwwroot
folder and load it through HTTP request.You can refer to this example:
I created appsettings.override.json
in the wwwroot folder:
appsettings.override.json:
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"System": "Information",
"Microsoft": "Error"
}
},
"TestSetting": "This is a test setting value from appsettings.override.json",
}
Use HTTP request to load it in 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();
Show the TestSetting
in the configuration on the page test:
@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++;
}
}