我们如何在asp.net 5 JSON配置中使用CloudConfigurationManager?

问题描述 投票:15回答:1

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

同时,在Azure土地上,我们有这个漂亮的CloudConfigurationManager类,如果找不到Azure设置,它应该处理来自Azure网站设置或活动web.config的抓取设置。

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

azure-web-sites asp.net-core
1个回答
22
投票

好吧,事实证明,当使用CloudConfigurationManager和asp.net 5时,答案是你没有,并且样板代码已经涵盖了它。 (感谢Scott Hanselman在推特上回复我)

所以标准方法是这样的:

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");
© www.soinside.com 2019 - 2024. All rights reserved.