[英]How can I use config.json to set environment-specific variables for a Visual Studio 2015/DNX project?
我有一个Visual Studio 2015解决方案,由针对DNX框架的项目组成。 我一直在本地工作,但我计划部署到Azure环境(开发/测试/生产)。 自然,该解决方案使用不同的数据库连接字符串和其他取决于环境的变量。 过去,我使用云配置文件来设置这些变量,并使用CloudConfigurationManager
读取它们。
据了解,我需要使用config.json文件。 我的Startup.cs文件中包含以下代码:
public Startup(IHostingEnvironment env, IApplicationEnvironment app)
{
Configuration = new ConfigurationBuilder(app.ApplicationBasePath)
.AddJsonFile("config.json")
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
Configuration.Set("ASPNET_ENV", "Development");
}
我的config.json文件当前是一个空对象{ }
。 如何将变量添加到此文件(语法?),以及如何从代码访问变量?
在启动代码中注意以下行:
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
这将添加一个附加的JSON配置文件,该文件的名称取决于您的环境名称。 因此,将一个新文件添加到您的项目中:
config.<environment-name>.json
并在其中设置详细信息,例如:
{
"AppSettings": {
"SomeVariable": "Blah"
},
"Data": {
"YourConnectionString": {
"ConnectionString": "<connection string here>"
}
}
}
为了阅读配置,这里有一个很好的答案: 在mvc6中全局使用IConfiguration
您可以为此使用普通的旧JSON。 例如,以下是定义连接字符串的方法:
{
"Foo": "Bar"
}
要访问配置值,请执行以下操作:
config.Get("username")
要么:
config["username"];
您可以在此处找到更多信息: http : //docs.asp.net/en/latest/fundamentals/configuration.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.