在 Azure 中使用 GetEnvironmentVariable 读取 local.settings.json 中的 ConnectionStrings

Pரத*_*ீப் 5 environment-variables azure azure-functions

在Azure函数v1local.settings.json中,我尝试使用GetEnvironmentVariable静态方法读取存在的连接字符串

这是我的local.settings.json文件

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
  },
  "ConnectionStrings": {
    "OnPremisesConnection": "Server=test;Initial Catalog=testdb;Integrated Security=SSPI;"
  }
}
Run Code Online (Sandbox Code Playgroud)

使用以下代码读取连接字符串

string variableName = "OnPremisesConnection";
var res = Environment.GetEnvironmentVariable($"ConnectionStrings:{variableName}")
Run Code Online (Sandbox Code Playgroud)

但我得到了NULL结果。我在这里缺少什么?

小智 0

好的。您可以尝试下一个:

var config = new ConfigurationBuilder()
            .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables()
            .Build();
 
 string connectionStr = config["ConnectionStrings:OnPremisesConnection"]
Run Code Online (Sandbox Code Playgroud)