avi
avi

Reputation: 441

How to use appsettings.local.json?

I have created an appsettings.local.json to my project. In my start up file - configure method, I have added the below code:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        var builder = new ConfigurationBuilder()
      .SetBasePath(env.ContentRootPath)
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) //load base settings
      .AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true) //load local settings
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) //load environment settings
      .AddEnvironmentVariables(); 
    }

My application is still reading the original appsettings.json file and not the connection string from appsettings.local.json.
Did I miss out anything?

Upvotes: 1

Views: 5263

Answers (1)

Sergey Nazarov
Sergey Nazarov

Reputation: 706

ConfigurationBuilder used for create configuration by your own. If you want do it, you should move your code to Startup constructor and after that add next line:

Configuration = builder.Build();

Where Configuration is name of your IConfiguration property.

If you still want inject IConfiguration to you Startup constructor you can use this code at you IHostBuilder at Program.cs:

.ConfigureAppConfiguration((context, builder) =>
            {
                builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile("appsettings.local.json", optional: true,
                        reloadOnChange: true) 
                    .AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json",
                        optional: true)
                    .AddEnvironmentVariables();
            })

Please check context.HostingEnvironment.EnvironmentName for you framework version: my sample for netcoreapp3.1.

Upvotes: 1

Related Questions