Search code examples
asp.net-core-2.2

Options Pattern and User Secrets (Asp Core 2.2.)


I want to access my project´s user secrets with the options pattern. But when I use the options pattern the secret values is null; but my other configurations options work well.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettingsData>(Configuration);        
    services.Configure<MyUserSecrets>(Configuration);
}

MyController.cs

MyController(    
    IOptionsMonitor<MyUserSecrets> myUserSecrets
){
    _mySecrets = myUserSecrest.CurrentValue;
}

According to the documents I should add AddUserSecrets to builder, my builder look different from the example code. Here us my builder:

Program.cs

var builder = CreateWebHostBuilder(args);
builder.add // No AddUserSecrest available...
builder.Build().Run(); 

Solution

  • In order to get the subsections from appsettings the option need to ask the configuration to get the section.

    services.Configure<AppSettingsData>(Configuration); 
    services.Configure<MyUserSecrets>(Configuration.GetSection("MyUserSecrets"));