PAYATHON 2026

ASP.NET Core 运行时动态配置与占位符替换

数据小陈

结论:不要继承 ConfigurationSection,也不要把 IConfigurationSection 强转成自定义配置类。ConfigurationSection 属于旧的 System.Configuration XML 配置类型;builder.Configuration.GetRequiredSection("SoapService") 返回的是 IConfigurationSection,两者没有继承关系,强制转换会抛 InvalidCastException。正确做法是定义 POCO,用 Get<T>() 或 Options 绑定,并在注册使用方之前完成占位符替换。如果其他组件会直接读取 IConfiguration,可以在 builder.Build() 之前用 AddInMemoryCollection 覆盖具体的配置键。

1. 定义配置模型

public sealed class SoapServiceOptions
{
    public string SoapScheme { get; set; } = "https";
    public string SoapServiceHost { get; set; } = "";
    public CustomerAccountManagerOptions CustomerAccountManager { get; set; } = new();
}

public sealed class CustomerAccountManagerOptions
{
    public string Endpoint { get; set; } = "";
    public string Username { get; set; } = "";
    public string Password { get; set; } = "";
    public int TimeoutSeconds { get; set; } = 30;
    public long MaxReceivedMessageSize { get; set; } = 10485760;
}

2. 读取配置并替换占位符

这一步要在 builder.Build() 之前执行。Microsoft.Extensions.Configuration 不会自动展开 {SoapScheme} 这类占位符,需要自行替换。

var section = builder.Configuration.GetRequiredSection("SoapService");
var soap = section.Get<SoapServiceOptions>() ?? new SoapServiceOptions();

// 这里放你的判断逻辑,例如检查服务是否运行
var serviceRunning = IsServiceRunning();
var host = serviceRunning ? soap.SoapServiceHost : "SoapFallbackService";

var endpoint = soap.CustomerAccountManager.Endpoint
    .Replace("{SoapScheme}", soap.SoapScheme)
    .Replace("{SoapServiceHost}", host);

builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
    ["SoapService:CustomerAccountManager:Endpoint"] = endpoint
});

AddInMemoryCollection 是后添加的配置提供程序,会覆盖前面同名的键。覆盖完成后,其他组件再从 IConfiguration 读取时,拿到的就是新值。

3. 绑定到 Options

builder.Services.Configure<SoapServiceOptions>(
    builder.Configuration.GetSection("SoapService"));

如果不想把替换后的值写回 IConfiguration,也可以只在 Options 的后处理里替换:

builder.Services.AddOptions<SoapServiceOptions>()
    .Bind(builder.Configuration.GetSection("SoapService"))
    .PostConfigure(options =>
    {
        options.CustomerAccountManager.Endpoint =
            options.CustomerAccountManager.Endpoint
                .Replace("{SoapScheme}", options.SoapScheme)
                .Replace("{SoapServiceHost}", options.SoapServiceHost);
    });

任选一种即可,不要同时依赖两套替换逻辑。

4. 运行时更新

如果配置需要在运行期间变化,可以注入 IOptionsMonitor<SoapServiceOptions> 获取当前值。自定义配置源可以更新 IConfigurationRoot 后调用 Reload()。要注意,IOptions<T> 默认是单例快照,不适合需要动态变化的场景。

注意事项

  • 配置键用 :,环境变量通常用 __ 映射层级。
  • GetRequiredSection 返回的是接口,不能强转为自定义类。
  • 不要在日志中输出 Password。
  • 如果服务运行检查涉及网络 IO,避免在启动路径上同步阻塞;可以考虑健康检查、延迟创建客户端,或改用 IOptionsMonitor。
  • Aspire AppHost 通过环境变量或参数注入配置时,应用内仍然从 builder.Configuration 读取;不要在 ASP.NET 应用里修改 AppHost 配置。

备注:内容仅供参考。