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

.NET 8中如何让服务访问强类型配置类里的AllowedHosts等值?

解决方案(.NET 8)

1. 接入Azure App Configuration配置源

在Program.cs中添加Azure App Configuration作为配置源,同时指定要加载的目标配置键前缀:

var builder = WebApplication.CreateBuilder(args);

// 连接Azure App Configuration并加载指定前缀的配置项
builder.Configuration.AddAzureAppConfiguration(options =>
{
    options.Connect("你的Azure App Config连接字符串")
           // 加载AppName前缀下的所有配置
           .Select("AppName:*", LabelFilter.Null)
           // 加载Logging前缀下的所有配置(适配日志级别需求)
           .Select("Logging:*", LabelFilter.Null);
});

2. 绑定强类型POCO并注入DI容器

将AppName前缀的配置绑定到你的AppConfigValues类,注册到依赖注入容器,让业务服务可以便捷获取:

// 绑定AppName节点配置到强类型类,注册为单例
builder.Services.Configure<AppConfigValues>(builder.Configuration.GetSection("AppName"));

业务服务中通过构造函数注入IOptions<AppConfigValues>即可访问配置值:

public class SampleService
{
    private readonly string? _allowedHosts;

    public SampleService(IOptions<AppConfigValues> appConfigOptions)
    {
        _allowedHosts = appConfigOptions.Value.AllowedHosts;
    }
}

3. 处理Logging:LogLevel配置

对于Logging:LogLevel这类.NET框架原生配置,只要在步骤1中加载了Logging:*前缀的配置项,框架会自动读取并应用这些日志级别设置,无需额外绑定操作,直接生效。

4. 配置源优先级说明

.NET配置系统会自动处理多源优先级,默认Azure App Configuration的配置优先级高于本地appsettings.json和环境变量(可通过调整配置源的添加顺序修改优先级),确保目标配置值被正确读取。

验证配置加载(可选)

可在Program.cs中临时输出配置值验证加载效果:

var allowedHosts = builder.Configuration["AppName:AllowedHosts"];
Console.WriteLine($"AllowedHosts: {allowedHosts}");

var defaultLogLevel = builder.Configuration["Logging:LogLevel:Default"];
Console.WriteLine($"Default Log Level: {defaultLogLevel}");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 19:37:05