Search code examples
c#asp.net-coreazure-application-settings

Use Application settings from Azure Web App directly, not from appsettings.Production.json


I would like to use App settings for Production environment, as defined in the Azure Web App: See here

Currently using appsettings*.json files to get these values in Program.cs for the correct environment:

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();

These values are currently defined in the json e.g.

"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"
  }

I tried to remove these from the appsettings.production.json to force it to use the ones supplied in Azure, but it errored. I would think that as it's set up in Program.cs it will always search for the settings in the relevant environment json file.

How do I overwrite this in config to use the application settings? Preferably for Production environment only.


Solution

  • Well, I'm not sure if this is actually the issue, but it's useless code anyways. CreateDefaultBuilder, among other things, configures various configuration providers, including for appsettings.json and appsettings.{environment}.json. It then goes on to add things like environment variables.

    At the best, there's no reason for your call to ConfigureAppConfiguration, as those files are already being added via the call to CreateDefaultBuilder. However, there's also an order of ops to how configuration is added: namely configuration providers added later override those added previously. As such, by adding your JSON files again like this, you're actually making them the last config provider included, meaning they override everything. The App Settings in Azure are added as environment variables, I believe. That would normally make them override anything your JSON files, as the environment variable provider is added after the JSON providers. However, you've flipped the script now, making them overridden by the JSON.

    I'm not sure why removing them from your JSON would result in an error, but I'm reasonably sure that simply removing the ConfigureAppConfiguration call should just make everything work as intended.