skip to Main Content

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


  1. Chosen as BEST ANSWER

    Found the answer in the documentation.

    One simply needs to add the Microsoft.Extensions.Options.ConfigurationExtensions nuget package to the Blazor WASM project.


  2. Make use of IConfiguration.Get<> it is an extension method.

    Let say I wanted to load a C# model called ChatSettings.cs

    public class ChatSettings
    {
        public string BaseUrl { get; set; }
        public string Scope { get; set; }
    }
    

    I update my appsettings to look like this:

    {
      ...
      "Chat": {
        "BaseUrl": "https://localhost:7040/",
        "Scope": "api://xxxx-xxx-xxxx-xxxx-xxxxxx/access_as_user"
      }
      ...
    }
    

    Now create a model for the root of your appsettings.json

    public class LocalConfigurations
    {
        public ChatSettings Chat { get; set; }
    }
    

    In program.cs

        var config = builder.Configuration.Get<LocalConfigurations>();
    

    If you wish to access this info from another service or razor component add this

        builder.Services.AddSingleton(_ => config);
    

    In a service just add it to your constructor.

    public class SomeService 
    {
        public SomeService(LocalConfigurations config)
        {
            ChatSettings chatConfig = config.Chat;
        }
    }
    

    In a .razor file use the @inject or [Inject] attribute on the property

    @inject LocalConfigurations Config
    
    ...
    
    @code {
        [Inject]
        private LocalConfigurations Config { get; set; }
    }
    
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search