0

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

2
  • what kind of application it is. console app or web api ? and if web api which version of .NET 5 or 6? Commented Jun 30, 2022 at 9:51
  • net 6. WebAPi. updating inthe question as well Commented Jun 30, 2022 at 9:53

1 Answer 1

1

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>();
                });
Sign up to request clarification or add additional context in comments.

8 Comments

not working in my case still reading from normal appSettings
are you creating ConfigurationBuilder again or using like i have done.
Yes i am creating it again
why do you need to create again. and it is only local in your code block it is not getting assigned to actual configuration.
@Sana: I have updated the ans. if you are using old way of program.cs then you can update it there.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.