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

.NET 8 Azure Function中POCO无法读取local.settings.json值的问题

问题:无法将local.settings.json配置绑定到POCO对象

尝试将local.settings.json中的本地配置值读取到POCO对象FunctionAppConfig中,但绑定后对象未获取到任何值,该POCO用于注入到基础设施层和应用层的服务及扩展中。

相关代码

program.cs

using Ioc.Infrastructure.Extensions;
using Ioc.Application.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Cors.Infrastructure;
using System.Text.Json.Serialization;
using System.Text.Json;
using Ioc.Domain.Shared;
using Microsoft.Extensions.Configuration;

var host = new HostBuilder()
        .ConfigureFunctionsWorkerDefaults(builder =>
        {
            builder.Services.AddCors(options =>
            {
                options.AddPolicy("IocAppOrigins", policy =>
                {
                    policy.WithOrigins("http://localhost:4200")
                          .AllowAnyMethod()
                          .AllowAnyHeader();
                });
            });
        })
        .ConfigureServices(s => {
            s.AddHttpClient();
            s.Configure<JsonSerializerOptions>(options =>
            {
                options.AllowTrailingCommas = true;
                options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                options.PropertyNameCaseInsensitive = true;
            });
        })
        .ConfigureServices((context, services) =>
        {
            var myFunctionSettings = new FunctionAppConfig();
            context.Configuration.Bind("Values", myFunctionSettings);

            services.AddSingleton(myFunctionSettings);
            services.AddApplicationServices(myFunctionSettings);
            services.AddInfrastructureServices(myFunctionSettings);
        })
    .Build();

host.Run();

local.settings.json

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "KeyVaultUri": "https://yourkeyvaultname.vault.azure.net/",
    "SecretName": "YourSecretName",
    "SampleSecretKeyForTesting": "H1d7#f$812!F9)Jkq31p&*d9!@Ld3wE6",
    "ConnectionString": "Data Source=localhost\\SQLEXPRESS;Initial Catalog=ioc-prd;User ID=delphdbadminprd;Password=*******;Trust Server Certificate=True"
  },
  "ConnectionStrings": {
    "ConnectionString": "Data Source=localhost\\SQLEXPRESS;Initial Catalog=ioc-prd;User ID=delphdbadminprd;Password=********;Trust Server Certificate=True"
  },
  "Host": {
    "CORS": "http://localhost:4200"
  }
}

POCO类FunctionAppConfig

public class FunctionAppConfig
{
    public string KeyVaultUri { get; set; }
    public string SecretName { get; set; }
    public string SampleSecretKeyForTesting { get; set; }
    public string ConnectionString { get; set; }
    // Add other properties as needed
}

问题原因分析

  • 配置节点路径错误:在.NET Isolated模式的Azure Functions中,local.settings.json里的Values节会被直接加载到配置的根节点,而非作为一个子节点存在。因此使用context.Configuration.Bind("Values", myFunctionSettings)时,系统找不到名为Values的子节点,导致绑定失败。
  • 潜在的配置冲突:ConnectionString同时存在于Values和ConnectionStrings节,而ConnectionStrings的配置源优先级更高,可能导致最终读取的值不符合预期(不过这不是本次绑定失败的直接原因)。

解决方法

方法一:直接绑定根配置到POCO

修改ConfigureServices中的绑定代码,去掉"Values"参数,直接绑定根配置:

.ConfigureServices((context, services) =>
{
    var myFunctionSettings = new FunctionAppConfig();
    context.Configuration.Bind(myFunctionSettings); // 直接绑定根配置

    services.AddSingleton(myFunctionSettings);
    services.AddApplicationServices(myFunctionSettings);
    services.AddInfrastructureServices(myFunctionSettings);
})

方法二:使用强类型配置绑定(推荐)

这是.NET配置系统的标准用法,更符合依赖注入规范:

  1. 注册强类型配置:
.ConfigureServices((context, services) =>
{
    // 注册配置,自动绑定根配置到FunctionAppConfig
    services.Configure<FunctionAppConfig>(context.Configuration);

    // 如果需要直接获取实例注入到其他服务
    var settings = context.Configuration.Get<FunctionAppConfig>();
    services.AddSingleton(settings);

    services.AddApplicationServices(settings);
    services.AddInfrastructureServices(settings);
})
  1. 在需要使用配置的服务中,通过IOptions<T>注入:
public class YourInfrastructureService
{
    private readonly FunctionAppConfig _config;

    public YourInfrastructureService(IOptions<FunctionAppConfig> config)
    {
        _config = config.Value;
    }
}

额外注意

如果需要明确读取Values节中的ConnectionString而非ConnectionStrings节的值,可以在POCO类中添加配置特性指定路径:

public class FunctionAppConfig
{
    public string KeyVaultUri { get; set; }
    public string SecretName { get; set; }
    public string SampleSecretKeyForTesting { get; set; }

    [ConfigurationKeyName("Values:ConnectionString")]
    public string ConnectionString { get; set; }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 11:54:51