0

In my ASP.NET Core 6 project I have the following configuration files:

appsettings.json
appsettings.Development.json
appsettings.Production.json

Then in my Startup class I provide a constructor to get the configuration:

public Startup(IConfiguration config)
{
    this.Configuration = config;
}

I intend to use appsettings.json + appsettings.Development.json config in Debug and appsettings.json + appsettings.Production.json in Release.

I achieved this by using the following code in my CreateHostBuilder:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
           // ..
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
#if DEBUG
        .UseEnvironment("Development");
#else
        .UseEnvironment("Production");
#endif
}

Is there a better way to do this?

LA.27
  • 1,888
  • 19
  • 35
  • You should never store anything like passwords or database connection strings or similar in appsettings.json. There are bots looking through GitHub for sensitive data like this. When running locally, you should use UserSecrets (basically another json file, outside of the source code, which will never be committed to your source control). When deploying your code, the settings for your environment should be populated by the build server from a separate secure place, and the artifacts to be published on the server should only be stored somewhere secure. – Neil Jul 01 '22 at 18:46
  • Thanks, I use a personal git server, so this is not an issue in my case, but I'll take a look at UserSecrets. – LA.27 Jul 01 '22 at 19:34
  • Sounds like you are looking for environment specific transformation of your configuration file. Check out https://stackoverflow.com/questions/43073959/how-do-i-transform-appsettings-json-in-a-net-core-mvc-project – Amogh Sarpotdar Jul 01 '22 at 16:56

0 Answers0