加载子目录appsettings失败求助:other下的配置为何未生效?
问题分析与解决方案
你的核心问题是错误使用ConfigureHostConfiguration加载应用业务配置,同时忽略了Host.CreateDefaultBuilder的默认配置加载逻辑,导致子目录的配置文件被覆盖。
具体原因
配置层级优先级差异:
Host.CreateDefaultBuilder会自动加载两类配置:- 主机配置(
HostConfiguration):用于配置主机自身(如端口、环境变量前缀等),优先级较低。 - 应用配置(
AppConfiguration):用于业务配置,默认会加载根目录的appsettings.json、appsettings.{Environment}.json,优先级远高于主机配置。
- 主机配置(
- 你在
ConfigureHostConfiguration中添加的子目录配置文件,会被默认加载的AppConfiguration里的根目录appsettings.A.json覆盖。
配置加载顺序逻辑:
即使你在ConfigureHostConfiguration中按顺序添加了根目录和子目录的配置,但由于主机配置优先级低于应用配置,子目录的配置永远不会生效。
修正后的代码
将配置加载逻辑移到ConfigureAppConfiguration中,利用默认加载逻辑的同时,额外添加子目录配置文件(确保子目录配置覆盖根目录的):
IHostBuilder builder = Host.CreateDefaultBuilder().UseEnvironment("A"); builder.ConfigureAppConfiguration((hostContext, config) => { // 获取当前内容根目录 var contentRoot = hostContext.HostingEnvironment.ContentRootPath; // 添加子目录的配置文件,放在默认加载之后,确保优先级更高 config.AddJsonFile(Path.Combine(contentRoot, "other", "appsettings.A.json"), optional: true, reloadOnChange: true); }); builder.ConfigureServices((host, services) => services.Configure<Config>(host.Configuration)); IHost host = builder.Build(); Console.WriteLine(host.Services.GetService<IOptions<Config>>()!.Value.File); Console.ReadLine();
额外说明
- 如果需要完全自定义配置加载逻辑(不依赖默认的
appsettings加载),可以在ConfigureAppConfiguration中先清除默认配置源,再按顺序添加所需文件:builder.ConfigureAppConfiguration((hostContext, config) => { config.Sources.Clear(); var contentRoot = hostContext.HostingEnvironment.ContentRootPath; config .AddJsonFile(Path.Combine(contentRoot, "appsettings.json"), optional: false, reloadOnChange: true) .AddJsonFile(Path.Combine(contentRoot, "appsettings.A.json"), optional: true, reloadOnChange: true) .AddJsonFile(Path.Combine(contentRoot, "other", "appsettings.A.json"), optional: true, reloadOnChange: true) .AddEnvironmentVariables(); }); optional: true表示文件不存在时不会抛出异常,会自动回退到之前的配置;如果要求子目录文件必须存在,可改为optional: false。
内容的提问来源于stack exchange,提问作者Bin4ry
相关产品推荐
相关产品推荐

