Sana
Sana

Reputation: 447

Asp.net core: How to use appSettings for a particular environment

In .NET 6.0 WebApi application

I have the following two files: appSettings.json appSettings.Linux.json

I want the application to use appSettings.Linux.json when running in linux environment. The following is the code that I have tried so far but unfortunately it is not working. It is still accessing appSettings.json file while running in linux environment.

    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
    {
        IConfigurationBuilder builder = new ConfigurationBuilder()
                                            .AddJsonFile("appSettings.Linux.json" , optional: true, reloadOnChange: true);
        builder.Build();
    }

I am adding a new builder as follows enter image description here

Upvotes: 0

Views: 1352

Answers (1)

CodingMytra
CodingMytra

Reputation: 2600

in .NET 6, you can do like this.

if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
    builder.Environment.EnvironmentName = "Linux";
    builder.Configuration.AddJsonFile("appSettings.Linux.json");
}

and then it will override all the configuration values.

appsettings.Linux.json enter image description here

accessing value from Configuration enter image description here

Updated answer based on feedback.

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration(config =>
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        config.AddJsonFile("appSettings.Linux.json", optional: true, reloadOnChange: true);
                    }
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

Upvotes: 1

Related Questions