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

如何从local.settings.json获取Connectionstring值?已尝试方法均返回Null

解决local.settings.json自定义节点读取返回Null的问题

问题根源

Azure Functions的local.settings.json中,只有Values节点下的键值对会被自动加载到环境变量,也只有这个节点的内容能通过config.GetSection()、Environment.GetEnvironmentVariable()这类默认方法直接读取。你自定义的Connectionstring节点不在默认加载范围内,所以调用这些方法会返回Null。

解决方法

方法一:将连接字符串移到Values节点(推荐)

修改local.settings.json,把连接字符串放到Values里,可遵循Azure Functions的命名惯例(用ConnectionStrings:前缀):

{
    "Values": {
        "Name": "test",
        "ConnectionStrings:Myconnection": "myconnectionstring"
    }
}

读取方式:

  • 使用环境变量:
    string connStr = Environment.GetEnvironmentVariable("ConnectionStrings:Myconnection");
    
  • 使用配置对象:
    string connStr = config.GetSection("ConnectionStrings").GetValue<string>("Myconnection");
    // 或者直接取值
    string connStr = config.GetValue<string>("ConnectionStrings:Myconnection");
    

方法二:手动加载整个配置文件(仅本地调试用)

如果要保留原Connectionstring节点结构,需要手动构建配置对象来读取整个local.settings.json:

var configBuilder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables();

IConfiguration config = configBuilder.Build();
string connStr = config.GetSection("Connectionstring")["Myconnection"];

注意:这种方式仅适用于本地调试,部署到Azure时local.settings.json不会被上传,需在Azure门户的「配置」→「应用程序设置」中添加对应的连接字符串配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 01:02:37