在 Startup.cs 中可以设置多个配置源,可以使用 appsettings.json 之类的 json 文件,可以使用环境变量,还可以使用一个叫做 usersecrets 的新东西。添加它们的顺序很重要,因为每个配置源都可以复制相同的设置。
添加配置源越晚,它获得的优先级越高。考虑我自己项目中的这个示例,还可以查看 cmets:
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This reads the configuration keys from the secret store.
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
// this file name is ignored by gitignore in my project
// so you can create it and use on your local dev machine
// remember last config source added wins if it has the same settings
builder.AddJsonFile("appsettings.local.overrides.json", optional: true);
// most common use of environment variables would be in azure hosting
// since it is added last anything in env vars would trump the same setting in previous config sources
// so no risk of messing up settings if deploying a new version to azure
builder.AddEnvironmentVariables();
Configuration = builder.Build();
然后,就存储配置设置而言,您应该使用具有属性的类,这些属性可以在启动时从配置映射并注册到 DI 服务,以便可以在需要它们的任何地方注入它们。有关详细示例,请参阅this question。
更新:以下包来自我的 project.json 并且是所需/相关的包,智能感知与否这些当前有效:
"Microsoft.Extensions.Configuration": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Abstractions": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
"Microsoft.Extensions.OptionsModel": "1.0.0-rc1-final",
"Microsoft.Extensions.DependencyInjection.Abstractions": "1.0.0-rc1-final",