4

In my current application i am using the following setup to read all the values from appsetting.json

public class AppSettings
    {
        private static AppSettings _appSettings;
        public string RememberMeCookieName{ get; set; }
       
        public AppSettings(IConfiguration config)
        {
            
            this.RememberMeCookieName = config.GetValue<string>("RememberMeCookieName");
            
            _appSettings = this;
        }

        public static AppSettings Current
        {
            get
            {
                if (_appSettings == null)
                {
                    _appSettings = GetCurrentSettings();
                }

                return _appSettings;
            }
        }

        public static AppSettings GetCurrentSettings()
        {
            
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())

                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

                .AddEnvironmentVariables();
           
            IConfigurationRoot configuration = builder.Build();

            var settings = new AppSettings(configuration.GetSection("AppSettings"));

            return settings;
        }

now my issue is that even with .AddEnvironmentVariables(); the value from appsettings.json is being pick up instead of appsettings.Development.json Any help would be welcomed

1 Answer 1

1

Try adding a second .AddJsonFile call after the first, using string interpolation for the environment name:

.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)

This is assuming you have environment variable ASPNETCORE_ENVIRONMENT set to "Development".

Sign up to request clarification or add additional context in comments.

3 Comments

unfortunately i dont have access to env.EnvironmentName as this is in class library project , and not on the asp.net web app project i dont have access to IWebHostEnvironment env in this project
Ah, I wasn't paying close enough attention and didn't realize you weren't in Startup. In that case I would pull the environment variable directly in place of env.EnvironmentName: Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT").
Also, I don't think .AddEnvironmentVariables() does what you're thinking. According to the documentation it overwrites values in the appsettings files with environment variables that have the same keys. learn.microsoft.com/en-us/aspnet/core/fundamentals/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.