我有一个 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>"
}
}
}
要阅读配置,这里有一个很好的答案:Using IConfiguration globally in mvc6
关于c# - 如何使用 config.json 为 Visual Studio 2015/DNX 项目设置特定于环境的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32090597/