我正在Mac上运行.net core 2.1应用程序,并且试图访问我的用户密码应该覆盖的连接字符串。 .csproj文件包含一个guid
<UserSecretsId>{{Secret Guid}}</UserSecretsId>
添加用户密钥
dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Secret Connection String"
我创建了从我的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"]);
正如我之前所述,尝试访问值时,它不会用用户密码值替换这些值。请让我知道我在想什么。
答案 0 :(得分:6)
将配置源添加到ConfigurationBuilder
的顺序很关键-以后添加的那些优先于首先添加的那些。在您的示例中,您在AddUserSecrets
之前调用AddJsonFile
,这将导致JSON文件值覆盖用户秘密中定义的值。
出于完整性考虑,以下是固定版本:
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);
鉴于此,您可能还希望将AddEnvironmentVariables
调用移至稍后在配置设置中运行。