我们如何将 CloudConfigurationManager 与 asp.net 5 JSON 配置一起使用?

How do we use CloudConfigurationManager with asp.net 5 JSON configs?

Asp.net 5 有一个新的配置系统,它利用 json 文件进行设置。您必须使用新 Configuration class 的 .AddJsonFile(string fileName) 方法手动 select 要加载的 json 文件作为您的配置。

同时,在 Azure 领域,我们有这个漂亮的 CloudConfigurationManager class,它应该处理从 Azure 网站设置或活动 web.config(如果 Azure 设置)抓取设置没有找到。

但这两个东西如何协同工作?我找不到任何文档。我想在 Azure 中管理我的生产设置,但使用 config.json 进行本地调试。我在查找任何示例或文档时遇到了很多麻烦。

好吧,事实证明,当谈到将 CloudConfigurationManager 与 asp.net 5 一起使用时,答案是 你不需要,样板代码已经涵盖它。 (感谢 Scott Hanselman 在 Twitter 上回复我)

所以标准方法是这样的:

IConfiguration configuration = new Configuration()
  .AddJsonFile("config.json") // adds settings from the config.json file
  .AddEnvironmentVariables(); // adds settings from the Azure WebSite config

这些调用的顺序意味着环境变量中的设置将覆盖本地配置中的设置。要使用它,您所要做的就是确保 Azure 设置将模仿您的 Json 设置 - 所以如果您的 json 文件看起来像

{
  "AppSettings": {
    "ConnectionString": "blahblahblah"
  }
}

您希望在 Azure 中设置您的设置看起来像

Key: AppSettings:ConnectionString 
Value: blahblahblah

,然后您可以继续使用与本地配置完全相同的代码。

var connectionString = Configuration.Get("AppSettings:ConnectionString");