How to acess the appsettings in blazor webassembly
Inkkiller nailed it. You can simplify the call into IConfiguration without the APIHelper class and access it directly in Program.cs from the WebAssemblyHostBuilder.
appsettings:
{
"ServerlessBaseURI": "http://localhost:0000/",
}
Program.cs:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
string serverlessBaseURI = builder.Configuration["ServerlessBaseURI"];
}
This answer concerned blazor preview when blazor didn't support appsettings.json in wwwroot folder yet. You should use appsettings.json in wwroot folder now and
WebAssemblyHostBuilder.Configuration
. It also support per environment files (appsettings.{env}.Json).
I solve this issue by using a settings.json file store in the app wwwroot folder and register a task to get the settings :
Settings.cs
public class Settings
{
public string ApiUrl { get; set; }
}
wwwroot/settings.json
{
"ApiUrl": "https://localhost:51443/api"
}
Progam.cs
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddSingleton(async p =>
{
var httpClient = p.GetRequiredService<HttpClient>();
return await httpClient.GetJsonAsync<Settings>("settings.json")
.ConfigureAwait(false);
});
SampleComponent.razor
@inject Task<Settings> getsettingsTask
@inject HttpClient client
...
@code {
private async Task CallApi()
{
var settings = await getsettingsTask();
var response = await client.GetJsonAsync<SomeResult>(settings.ApiUrl);
}
}
This has advantages:
- Doesn't share the server's appsettings.json file which can be a security hole
- Configurable per environment