Home > Mobile >  How to get appsettings value in ConfigureAppConfiguration c#
How to get appsettings value in ConfigureAppConfiguration c#

Time:10-15

I have to set a configurable value in CreateHostBuilder either from appsettings or any way; I just tried using appsettings

public static IHostBuilder CreateHostBuilder(string[] args) =>
                 Host.CreateDefaultBuilder(args)
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>();
                        webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
                        {
                            var url = _configuration.GetSection("url");
                            config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddOcelot(// Set url here)

                               .AddEnvironmentVariables();
                        });

                    });

But url value always returns as null. Does anyone has better solution to get appsetings in ConfigureAppConfiguration or any better idea to use any other idea to set configuration value?

CodePudding user response:

try this

Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
             .ConfigureServices((hostContext, services) =>
             {
                 IConfiguration configuration = hostContext.Configuration;
                  var url = configuration.GetSection("url");
             });

CodePudding user response:

You can change like below:

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
        webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
        {
            var settings = config.Build();
            var url = settings.GetSection("url").Value;

        });

    });
  • Related