直接从Azure Web App使用应用程序设置,而不是从appsettings.Production.json使用

时间:2019-04-04 15:48:39

标签: c# asp.net-core azure-application-settings

我想使用Azure Web App中定义的生产环境的App设置: See here

当前使用appsettings*.json文件在Program.cs中为正确的环境获取这些值:

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((builderContext, config) =>
        {
            IHostingEnvironment env = builderContext.HostingEnvironment;

            config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
               .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
        })
        .UseStartup<Startup>()
        .Build();

这些值当前在json中定义,例如

"ConnectionStrings": {
    "LocalizationAdminContext": "Data Source=example;Initial Catalog=example;Integrated Security=True;MultipleActiveResultSets=True"
  },
  "DbResourceConfiguration": {
    "ConnectionString": "Data Source=example;Initial Catalog=example;Integrated Security=True;MultipleActiveResultSets=True"
  }

我试图从appsettings.production.json中删除这些文件,以强制其使用Azure中提供的文件,但出现错误。我认为,由于它是在Program.cs中设置的,因此它将始终在相关环境json文件中搜索设置。

如何在config中覆盖此设置以使用应用程序设置?仅适用于生产环境。

1 个答案:

答案 0 :(得分:0)

好吧,我不确定这是否确实是问题所在,但无论如何它都是无用的代码。 CreateDefaultBuilder除其他事项外,还为appsettings.jsonappsettings.{environment}.json配置各种配置提供程序。然后继续添加诸如环境变量之类的东西。

充其量,您没有理由调用ConfigureAppConfiguration,因为这些文件已经通过调用CreateDefaultBuilder添加了 。但是,如何添加配置也有一个操作顺序:即后来添加的配置提供程序会覆盖以前添加的配置提供程序。这样,通过像这样再次添加JSON文件,实际上是在使它们成为包含的 last 配置提供程序,这意味着它们将覆盖所有内容。我相信,Azure中的“应用程序设置”已作为环境变量添加。通常,这会使它们覆盖您的JSON文件中的任何内容,因为环境变量提供程序是在JSON提供程序之后添加的。但是,您现在已经翻转了脚本,使它们被JSON覆盖。

我不确定为什么将其从JSON中删除会导致错误,但是我有把握地确定,仅删除ConfigureAppConfiguration调用就可以使一切正常工作。