Welcome to today’s post.
In today’s post I will be showing how to use application settings in a Blazor WebAssembly application.
In this post I will show how to create an application settings file, specify application settings keys, and apply their use within a Blazor WebAssembly file within Razor components and service classes.
In client and server applications, the way in which we retrieve configuration settings and use them within an application is quite similar, however the way in which the configuration settings are stored within an application are different. In addition, the security of settings in a server hosted application and a client hosted application will also differ.
In the first section I will first discuss the differences between a server hosted Blazor application and a client hosted Blazor application.
Difference between Configuration Settings in Blazor Server and Blazor WebAssembly Applications
In this section I will cover some differences between configurations used in server and client Blazor applications.
The first difference is where application configuration files are in the respective environments.
Location of Application Configuration Files
In a Blazor server environment, application settings files are stored within the same folder that the application binaries and library files are deployed to. In the Blazor server project, the application settings are stored in the project root folder of the application source. When the application is deployed to a web server, such as IIS, the application binaries, libraries, and configuration files are deployed to the wwwroot sub-folder of the web application.
In a Blazor client environment, the default application settings file appsettings.json and other custom application settings files are stored within the wwwroot sub-folder that includes an index.html landing page. Application binaries and library files are located on the web server and render content from Razor pages that are downloaded to the client browser environment.
Security of Application Configuration Files
In a client environment, the Blazor WebAssembly web application is downloaded into the internet download folder when it is accessed by a browser client. The code and application settings are downloaded into the wwwroot folder that is also downloaded. What this means is that the configuration file settings are accessible by any user who uses the Blazor WebAssembly application from within a browser.
Because of the accessibility of the application settings from any users downloaded content, sensitive application settings should not be stored within the application settings. It is safe to store API endpoints, or even customizable features like user interface sizes or colors within the application settings, but you should avoid storing connection strings, access keys, credentials, and passwords. Where access to server resources is required within a Blazor WebAssembly web client, the user should be provided with a login screen to enter credentials and a token issued to allow the client web application to request data and resources from the server through an API endpoint.
Setup of Application Configuration and Specifying Settings
Settings Keys in the Root Node of the JSON Configuration
Application configuration files such as the appsettings.json file are stored within the client’s wwwroot sub-folder. The configuration file has a JSON structure, with key and value pairs that correspond to application settings keys and values in the root node of the JSON structure.
Below is an example JSON settings keys that define API endpoints within an application:
{
"UrlBackendAPI": "http://localhost:5188/api/BookLoan",
"UrlBackendValidationAPI": "http://localhost:5188/api/BookLoanValidation"
}
The structure of the configuration files and settings keys is identical to that for server hosted web applications such as Blazor Server Web Applications and ASP.NET Core Web Applications.
Whan a server hosted web application is run the configuration settings are automatically read in by the application pipeline in its startup/bootstrap sequence in the Program.cs file. Application settings are retrievable within the application through the declaration of a Configuration class.
In the next section I will show how to use the Configuration class to configure and read the key and value settings values within client classes and Razor components.
Settings Keys in an Element Node of the JSON Configuration
There is another way in which you can specify configuration keys and values in the JSON configuration structure. Instead of using keys and values within the root node of the JSON structure, you can create a separate JSON element for each configuration section and move the key and value pairs into the section. The API endpoints that we had in the root node can be moved into the new JSON element ApiEndpoints as shown:
{
"ApiEndpoints": {
"UrlBackendAPI": "http://localhost:5188/api/BookLoan",
"UrlBackendValidationAPI": "http://localhost:5188/api/BookLoanValidation"
}
}
Whan a server hosted web application is run the configuration settings declared within a section node are still read in by the application pipeline in its startup/bootstrap sequence in the Program.cs file. Application settings are retrievable within the application through the declaration of an IConfiguration interface, however, to retrieve key and value pairs from the section, you would need to specify the section using the IConfiguration interface like this:
var apiEndpointSection = Configuration.GetSection("ApiEndpoints ");
The above then allows us to read off the keys and values.
In the next section I will show how to use the Options pattern to configure and read the key and value settings values within client classes and Razor components.
Reading of Default Configurations from Application Settings
In this section I will show how to read settings in the root node of the appsettings.json configuration file.
To read settings from the root node of the configuration file, there is no need to add any extra code in the startup code to map keys and values to the .NET Core Configuration class. I will show how to read keys and values from a client C# class and from a Razor component.
Reading Default Settings from a Client Class
To read configurations from a client class, you will need to declare an IConfiguration interface as a member and inject the application configuration in through the constructor with a parameter of the same interface type.
To retrieve the string value of the key, you would use the following code:
_configuration.GetValue<string>(key_name);
where:
key_name is the name of the settings key you want to retrieve.
The example below shows you how this is done:
BookService.cs
using BookLoanBlazorHostedWASMApp.Models;
using System.Net.Http.Json;
namespace BookLoanBlazorHostedWASMApp.Services
{
public class BookService : IBookService
{
private readonly ILogger _logger;
private readonly IHttpClientFactory _clientFactory;
private readonly IConfiguration _configuration;
private readonly string _apiUri;
public BookService(
ILogger<BookService> logger, IHttpClientFactory clientFactory, IConfiguration configuration)
{
_logger = logger;
_clientFactory = clientFactory;
_configuration = configuration;
_apiUri = _configuration.GetValue<string>("UrlBackendAPI");
}
public async Task<List<BookViewModel>> GetBooks()
{
var client = _clientFactory.CreateClient("BookLoanBlazorHostedWASMApp.ServerAPI");
var books = await client.GetFromJsonAsync<List<BookViewModel>>(_apiUri);
return books!.ToList();
}
public async Task<BookViewModel> GetBook(int id)
{
var client = _clientFactory.CreateClient("BookLoanBlazorHostedWASMApp.ServerAPI");
var book = await client.GetFromJsonAsync<BookViewModel>($"{_apiUri}/{id}");
return book!;
}
..
}
}
In the next section, I will show how to achieve the same default settings retrieval from a Razor component.
Reading Default Settings from a Razor Component
To read configurations from a Razor component, you will need to inject an IConfiguration interface into the component and use the instance variable to access the key and value settings using the same GetValue<Type>(key) method we used in the previous section.
Config.GetValue<string>( key_name);
where:
key_name is the name of the settings key you want to retrieve.
The example below shows you how this is done in a Razor component:
\BookLoanBlazorHostedWASMApp\Client\Pages\CreateBook.razor
@page "/createbook"
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Forms
@using BookLoanBlazorHostedWASMApp.Models
@using BookLoanBlazorHostedWASMApp.Services
@using BookLoanBlazorHostedWASMApp.Client.Validators
@inject IBookService LibraryBookService
@using System.Net
@inject HttpClient Http
@inject NavigationManager PageNavigation
@inject ILogger<CreateBook> Logger
@inject IConfiguration Config
<PageTitle>Create Book</PageTitle>
<h3>Create Book</h3>
..
@code {
private BookViewModel book = new();
private BookCreateModel? createbook;
private CustomValidation? customValidation;
..
private string apiEndpoint;
protected override async Task OnInitializedAsync()
{
createbook = new BookCreateModel(book);
apiEndpoint = Config.GetValue<string>("UrlBackendValidationAPI");
}
// Create entered book.
private async void SaveBook()
{
customValidation?.ClearErrors();
try
{
var response = await Http.PostAsJsonAsync<BookCreateModel>(
apiEndpoint, (BookCreateModel)createbook);
..
}
The above has shown us how to retrieve configuration settings using the default Configuration pattern. In the next section, will show how to retrieve configuration settings using the Options pattern.
Reading of Settings from Application Configuration Sections
In this section I will show how to read settings in an element node of the appsettings.json configuration file.
To read settings from an element (section) node of the configuration file, even though there is no need to add any extra code in the startup code to map keys and values to the .NET Core Configuration class, you make the retrieval cleaner, you can use a C# class definition to store the settings in the running application service collection. The settings can then be injected into a class or Razor component when needed.
I will show how to read keys and values from a client C# class and from a Razor component.
Configuring Options Configuration within the Application Startup
Before the application can read in the settings section from the mapped C# class, we will need to first declare and add a C# class to the project. A class with endpoints is shown below.
AppConfiguration.cs:
namespace BookLoanBlazorHostedWASMApp.Client.Services
{
public class AppConfiguration
{
public string UrlBackendAPI { get; set; }
public string UrlBackendValidationAPI { get; set; }
}
}
The startup class uses the builder.Services.Configure<Type>() method to retrieve the key-value pairs from the configuration section node and map them to the class of type Type. It then uses the builder.Services.AddSingleton<Type>() method to add the C# class as a mapped single instance the service collection.
This is shown below:
Program.cs:
using BookLoanBlazorHostedWASMApp.Client;
using BookLoanBlazorHostedWASMApp.Client.Services;
using BookLoanBlazorHostedWASMApp.Data;
using BookLoanBlazorHostedWASMApp.Services;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.Configure<AppConfiguration>(
builder.Configuration.GetSection("ApiEndpoints"));
builder.Services.AddSingleton<AppConfiguration, AppConfiguration>();
In the next section I will show how configuration sections are retrieved from a C# client class.
Reading Configuration Section Settings from a Client Class
To read settings from a client class we use the same method as we would use for any ASP.NET Core server application. This involves using the Options dependency injection pattern. We first install the following NuGet package into the Client project:
Microsoft.Extensions.Options.ConfigurationExtensions
Next, in our class source file, we declare usage of the following namespace:
Microsoft.Extensions.Options
We declare an internal typed IOptions variable of the C# configuration class as shown:
IOptions<AppConfiguration>
We then pass in a parameter of the same type into the constructor and assign it to the internal typed variable.
Access to settings values is then through the Value property as shown:
_apiUri = _appConfigOptions.Value.UrlBackendAPI;
An example of how this is done is shown below:
BookService.cs:
using Microsoft.Extensions.Options;
using System.Net.Http.Json;
namespace BookLoanBlazorHostedWASMApp.Services
{
public class BookService : IBookService
{
private readonly ILogger _logger;
private readonly IHttpClientFactory _clientFactory;
private readonly IConfiguration _configuration;
private readonly IOptions<AppConfiguration> _appConfigOptions;
private readonly string _apiUri;
public BookService(
ILogger<BookService> logger, IHttpClientFactory clientFactory,
IConfiguration configuration,
IOptions<AppConfiguration> appConfigOptions)
{
_logger = logger;
_clientFactory = clientFactory;
_configuration = configuration;
_appConfigOptions = appConfigOptions;
_apiUri = _appConfigOptions.Value.UrlBackendAPI;
}
..
When the above class is debugged, the retrieved settings values should show as follows:

Reading Configuration Section Settings from a Razor Component
To read settings from a Razor component class we use a similar method as we did for the C# class.
We first declare the following namespace:
@using Microsoft.Extensions.Options
Then declare and inject an internal typed IOptions variable of the C# configuration class into a variable instance as shown:
@inject IOptions<AppConfiguration> AppConfig
Accessing settings values is done in the component initialization through the Value property as shown:
apiEndpoint = AppConfig.Value.UrlBackendValidationAPI;
An example showing how this is done is shown below:
@using Microsoft.Extensions.Options
@inject IOptions<AppConfiguration> AppConfig
...
private string apiEndpoint;
protected override async Task OnInitializedAsync()
{
createbook = new BookCreateModel(book);
apiEndpoint = AppConfig.Value.UrlBackendValidationAPI;
}
private async void SaveBook()
{
customValidation?.ClearErrors();
try
{
var response = await Http.PostAsJsonAsync<BookCreateModel>(
apiEndpoint, (BookCreateModel)createbook);
..
When the above Razor component is debugged, the retrieved settings values should show as follows:

We have seen how to use the settings capability of a hosted Blazor WebAssembly application client.
We have seen how to retrieve settings from both the root node of a JSON settings configuration file and retrieve settings from a section node within the configuration file.
As I mentioned in the section on configuration security, care must be exercised in determining what settings to include in the configuration file.
That is all for today’s post.
I hope that you have found this post useful and informative.
Andrew Halil is a blogger, author and software developer with expertise of many areas in the information technology industry including full-stack web and native cloud based development, test driven development and Devops.