Search code examples
c#blazorblazor-client-side

How to acess the appsettings in blazor webassembly


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

Solution

  • 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.GetFromJsonAsync<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.GetFromJsonAsync<SomeResult>(settings.ApiUrl);
        }
    }
    

    This has advantages:

    • Doesn't share the server's appsettings.json file which can be a security hole
    • Configurable per environment