How to acess the appsettings in blazor webassembly

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://learn.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

Leave a Comment

tech