'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 1:[1]

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

Solution 2:[2]

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"];
}


Solution 3:[3]

You can also just (appsettings.json in wwwroot):

public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebAssemblyHostBuilder.CreateDefault(args);
        builder.RootComponents.Add<App>("app");

        var url = builder.Configuration.GetValue<string>("ApiConfig:Url");
        builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(url) });
    }
}

Solution 4:[4]

Using ASP.NET Core 6.0 Blazor configuration. Blazor WebAssembly loads configuration from the following app settings files by default:

  • wwwroot/appsettings.json.
  • wwwroot/appsettings.{ENVIRONMENT}.json, where the {ENVIRONMENT} placeholder is the app's runtime environment.

Example:

wwwroot/appsettings.json

{
  "h1FontSize": "50px"
}

Pages/ConfigurationExample.razor

@page "/configuration-example"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<h1 style="font-size:@Configuration["h1FontSize"]">
    Configuration example
</h1>

Warning Configuration and settings files in a Blazor WebAssembly app are visible to users. Don't store app secrets, credentials, or any other sensitive data in the configuration or files of a Blazor WebAssembly app.

https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/configuration?view=aspnetcore-6.0

You can also bind the values to a class.

public class ClientAppSettings
{
    public string h1FontSize{ get; set; }
}

Then add this class as a Singleton in Program.cs:

var settings = new ClientAppSettings();
builder.Configuration.Bind(settings);
builder.Services.AddSingleton(settings);

Add namespace to _Imports.razor and then inject where needed to get settings with autocomplete in Visual Studio:

@inject ClientAppSettings ClientAppSettings

Solution 5:[5]

As of now, you can use the IConfiguration.

appsettings.json:

{
  "Services": {
    "apiURL": "https://localhost:11111/"
  }
}

.

using Microsoft.Extensions.Configuration;

public class APIHelper
    {
        private string apiURL;

        public APIHelper(IConfiguration config)
        {
            apiURL = config.GetSection("Services")["apiURL"];
            //Other Stuff
        }

    }

Solution 6:[6]

Blazor WASM appsettings.json

If you dont have appsettings.json in the wwwroot folder then simply:

  1. Right click on wwwroot folder.
  2. Click Add ==> New Item ==> App Settings File

This will add appsettings.json to your application. Open the appsettings.json file you will see a section in it already for database add a section like I have added apiinfo:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

  "apiinfo":{
    "apiurl": "your api url"
  }

}

Now when you want to call this section simply Inject configuration and call it like:

@inject Microsoft.Extensions.Configuration.IConfiguration config;

And to call the apiurl:

config.GetSection("apiinfo")["apiurl"].ToString()

Solution 7:[7]

as an example, I have it implemeneted like this (client-side Blazor):

appsettings.json:

{
    "api": "https://www.webapiurl.com/"
    "ForceHTTPS": false
}

then, have typed config class

 public class APISetting
    {

        public string api { get; set; }

        public bool ForceHTTPS { get; set; }

    }

then, load on startup:

public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(GetConfiguration());
        }
        public void Configure(IComponentsApplicationBuilder app )
        {
            app.AddComponent<App>("app");
        }

        public APISetting GetConfiguration()
        {
            using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("appsettings.json"))
            using (var reader = new System.IO.StreamReader(stream))
            {
                return System.Text.Json.JsonSerializer.Deserialize<APISetting>(reader.ReadToEnd());
            }
        }
    }

Solution 8:[8]

create settings class:

public class Settings
{
    public string ApiUrl { get; set; }
}

create settings.json in wwwroot folder:

{
    "ApiUrl": "http://myapiurlhere"
}

and in .razor component read it like this:

@inject HttpClient Http
...
@code {
    private string WebApuUrl = "";

    protected override async Task OnInitializedAsync()
    {
        var response = await Http.GetFromJsonAsync<Settings>("settings.json");
        WebApuUrl = response.ApiUrl;
    }
}

Solution 9:[9]

Also in .Net 5 & 6 you can set the value to Static Class.

Example:

wwwroot/appsettings.json

 "ServicesUrlOptions": {
   "Url": "https://domain.gr/services" }

Static Class

public static class ApplicationServicesSettings
{
    public const string ServicesUrl = "ServicesUrlOptions";
    public static ServicesUrlOptions ServicesUrlOptions { get; set; } = new ServicesUrlOptions();
}

public class ServicesUrlOptions
{
    public string Url { get; set; }
}

Finally bind the value at Program.cs

 builder.Configuration.GetSection(ApplicationServicesSettings.ServicesUrl).Bind(ApplicationServicesSettings.ServicesUrlOptions);

After in project you have access to key by

ApplicationServicesSettings.ServicesUrlOptions.Url

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 hubris
Solution 3 Sunday
Solution 4
Solution 5 tbdrz
Solution 6 zhulien
Solution 7 yob
Solution 8 Zviadi
Solution 9