Configuration and Blazor

In a previous post we looked at dependency injection within Blazor. One of the services available by default is an implementation of IConfiguration, hence to inject the configuration object we do the following

@inject IConfiguration Configuration

and we can interact with the configuration using a key, i.e.

@Configuration["SomeKey"]

For Blazor on the server we can simply add the key/value to the appsettings.json file, like this

"SomeKey":  "Hello World" 

By default Blazor WebAssembly does not come with an appsettings.json, so you’ll need to add one yourself. This file will need to be in the wwwroot folder as these files will be deployed at part of your client.

You can put sensitive data in the server appsettings.json because it’s hosted on the server, do not put sensitive information in the appsettings.json for a WebAssembly/client otherwise this will be downloaded to the user’s machine.

If you want to store more complicated data in the appsettings.json, for example a JSON object, you’ll need to create a class that looks like the data, for example if your appsettings.json had the following

"Person": {
  "FirstName": "Scooby",
  "LastName": "Doo"
} 

So now we’ll need a class to match the structure of the data. The name of the class is not important, the structure is, so here we have

public class MyPerson
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

Now to access this we need to use

Configuration.GetSection("Person").Get<MyPerson>();

References

Carl Franklin’s Blazor Train: Configuration and Dependency Injection