I currentying trying to save the api url in an appsettings. However, the configuration.Propertiers seems to be empty. I am not sure how to get the setting. in program.cs:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
//string url = builder.Configuration.Properties["APIURL"].ToString();
foreach (var prop in builder.Configuration.Properties)
Console.WriteLine($"{prop.Key} : {prop.Value}" );
//builder.Services.AddSingleton<Service>(new Service(url));
builder.RootComponents.Add<App>("app");
await builder.Build().RunAsync();
}
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: