I’m wondering about the following:
In ASP.NET applications I access general configuration sections from appsettings.json
as follows for example:
builder.Services.Configure<FileUploadChecksModel>(builder.Configuration.GetSection("UploadChecks"));
Where FileUploadChecksModel
is a simple model class, which matches the respective section in appsettings.json
In a Blazor WASM project I can put appsettings.json
in wwwroot
to use it in the same way, however the same line of code as above throws the following error:
CS1503 Argument 2: cannot convert from ‘Microsoft.Extensions.Configuration.IConfigurationSection’ to ‘System.Action<Models.FileUploadChecksModel>’
Turns out the method builder.Services.Configure()
expects an IConfiguration
in other ASP.NET applications and Action<>
in a Blazor WASM project as an argument.
Question is why this is different here and how to best get the the data into my model in this case?
2
Answers
Found the answer in the documentation.
One simply needs to add the
Microsoft.Extensions.Options.ConfigurationExtensions
nuget package to the Blazor WASM project.Make use of
IConfiguration.Get<>
it is an extension method.Let say I wanted to load a C# model called ChatSettings.cs
I update my appsettings to look like this:
Now create a model for the root of your appsettings.json
In program.cs
If you wish to access this info from another service or razor component add this
In a service just add it to your constructor.
In a .razor file use the @inject or [Inject] attribute on the property
Use one method of injecting not both. I prefer the attribute way as I prefer the code behind approach.
You do not have to map everything in your appsettings just the properties you are interested in for "your" code. The deserialization will ignore the other attributes and only map the properties mentioned in your config classes.