.NET Core console application, how to configure appSettings per environment?

后端 未结 7 962
囚心锁ツ
囚心锁ツ 2020-12-04 14:15

I have a .NET Core 1.0.0 console application and two environments. I need to be able to use appSettings.dev.json and appSettings.test.json based on

7条回答
  •  遥遥无期
    2020-12-04 14:36

    If like me, you're simply trying to have a different configuration file for Release and Development mode, just add a appsettings.Development.json file with CopyToOutputDirectory setting set to true in the file's property window.

    Now, to access the file depending on the build configuration, you can use the #if DEBUG preprocessor directive.

    Here's an example :

    static void Main(string[] args)
    {
    
    #if DEBUG
        var builder = new ConfigurationBuilder()
                .AddJsonFile($"appsettings.Development.json", true, true);
    #else
        var builder = new ConfigurationBuilder()
                .AddJsonFile($"appsettings.json", true, true);
    #endif
    
        var configuration = builder.Build();
    
        // ... use configuration
    }
    

提交回复
热议问题