Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core 2.1 not reading User Secrets

I am running a .net core 2.1 application on a mac and I am trying to access my connections string which should be overridden by my user secrets. The .csproj file includes a guid

<UserSecretsId>{{Secret Guid}}</UserSecretsId>

Add the user secret keys

dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Secret Connection String"

I create the configuration which reads from my appsettings.json file perfectly however it does not replaces the default values with the ones from my user secrets.

// this is done so I build my configurations in a class library
var assembly = AppDomain.CurrentDomain.GetAssemblies()
    .Single(o => o.EntryPoint != null);

var configurationBuilder = new ConfigurationBuilder()
    .AddEnvironmentVariables()
    // .AddUserSecrets<Program>() -> This does not work either
    .AddUserSecrets(assembly, optional: false);

configurationBuilder.SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
var configuration = configurationBuilder.Build();

Console.WriteLine(configuration["ConnectionStrings:DefaultConnection"]);

As I stated previously trying to access the values it does not replace the values with the user secrets values. Please let me know what I am missing.

like image 230
Dblock247 Avatar asked Nov 24 '18 20:11

Dblock247


1 Answers

The order you add configuration sources to your ConfigurationBuilder is important - those added later override those added earlier. In your example, you're calling AddUserSecrets before AddJsonFile, which results in your JSON file values overriding your user secrets values.

For the sake of completeness, here's a fixed version:

var configurationBuilder = new ConfigurationBuilder()
    .AddEnvironmentVariables();

configurationBuilder.SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
configurationBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

// configurationBuilder.AddUserSecrets<Program>(); -> This does not work either
configurationBuilder.AddUserSecrets(assembly, optional: false);

In light of this, you might also want to move the AddEnvironmentVariables call to run later in the configuration setup.

like image 181
Kirk Larkin Avatar answered Nov 15 '22 12:11

Kirk Larkin