简体   繁体   English

.Net Core 2.1不读取用户秘密

[英].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. 我在mac上运行.net核心2.1应用程序,我试图访问我的连接字符串,应该被我的用户机密覆盖。 The .csproj file includes a guid .csproj文件包含一个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. 我创建了完全从我的appsettings.json文件中读取的配置,但它没有用我的用户机密中的值替换默认值。

// 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. 请让我知道我错过了什么。

The order you add configuration sources to your ConfigurationBuilder is important - those added later override those added earlier. 将配置源添加到ConfigurationBuilder的顺序非常重要 - 稍后添加的顺序将覆盖之前添加的顺序。 In your example, you're calling AddUserSecrets before AddJsonFile , which results in your JSON file values overriding your user secrets values. 在你的榜样,你打电话AddUserSecretsAddJsonFile ,这会导致你的JSON文件中的值覆盖用户的秘密值。

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. 鉴于此,您可能还希望将AddEnvironmentVariables调用移至稍后在配置设置中运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM