You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何在ConfigureAppConfiguration中读取appsettings配置值

问题根因

你在ConfigureAppConfiguration中直接调用的_configuration在当前阶段还未完成初始化构建,且你在还未加载配置源的前提下尝试读取配置,因此拿到的值始终为null。另外Host.CreateDefaultBuilder已经默认帮你加载了根目录下的appsettings.json、appsettings.{环境名}.json、环境变量等配置源,你代码中的重复注册AddJsonFile属于冗余操作。

可行解决方案

方案1:直接用宿主上下文已加载的配置读取(最简方案)

直接通过hostingContext.Configuration读取Host.CreateDefaultBuilder默认加载好的配置值即可,示例代码如下:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                // 直接通过宿主上下文读取已加载的配置
                string ocelotConfigUrl = hostingContext.Configuration.GetValue<string>("url");
                config.AddOcelot(ocelotConfigUrl)
                      .AddEnvironmentVariables();
            });
        });

方案2:手动构建临时配置读取

如果你自定义了配置文件路径/名称,没有用默认的加载规则,可以手动构建临时配置对象读取需要的参数:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                // 先构建临时配置对象读取需要的参数
                var tempConfig = new ConfigurationBuilder()
                    .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddEnvironmentVariables()
                    .Build();
                string ocelotConfigUrl = tempConfig.GetValue<string>("url");
                
                config.AddOcelot(ocelotConfigUrl)
                      .AddEnvironmentVariables();
            });
        });
注意事项
  • 确保appsettings.json文件的「复制到输出目录」属性设置为如果较新则复制,避免运行时找不到配置文件
  • 如果你要读取的是嵌套配置,需要写全配置路径,比如配置结构为{"Ocelot": {"ConfigUrl": "xxx"}},读取时需要写GetValue<string>("Ocelot:ConfigUrl")

内容的提问来源于stack exchange,提问作者luci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:54:04