如何在 ConfigureAppConfiguration c# 中获取 appsettings 值

How to get appsettings value in ConfigureAppConfiguration c#

我必须通过应用程序设置或任何方式在 CreateHostBuilder 中设置一个可配置的值;我刚刚尝试使用 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();
                        });

                    });

但是 url 值总是 returns 为空。 有没有人有更好的解决方案来获取 ConfigureAppConfiguration 中的应用设置,或者有更好的想法来使用任何其他想法来设置配置值?

试试这个

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

您可以如下更改:

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;

        });

    });