curiousprogrammer
curiousprogrammer

Reputation: 55

.NET 5.0 - How do I add to an existing configuration?

This is my Startup constructor in Startup.cs:

private readonly IWebHostEnvironment _hostingEnv;

private IConfiguration Configuration { get; }

public Startup(IWebHostEnvironment env, IConfiguration configuration)
{
    _hostingEnv = env;
    Configuration = configuration;
}

I want to be able to add a Json config file and build the configuration, something like this:

var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        Configuration = builder.Build();

But I want to add this to the existing configuration provided by the 'configuration' parameter, and not create a new configuration.

How do I do this?

I don't know from where this 'configuration' parameter is being passed to the Startup Constructor. This is what I have in my Program.cs file

public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 
    WebHost.CreateDefaultBuilder(args).UseStartup<Startup>()
    .UseUrls(new[] { "http://0.0.0.0:9999" });

Upvotes: 0

Views: 223

Answers (1)

Rena
Rena

Reputation: 36715

You could change your Program.cs like below:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            var env = hostingContext.HostingEnvironment;

            config.SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
         
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

Upvotes: 1

Related Questions