Azure函数将local.settings.json读取为对象

时间:2018-10-16 20:25:13

标签: c# json azure azure-functions

我知道我可以在local.settings.json的{}部分添加所有环境变量。但是,我正在努力保持整洁的家,并希望我能做这样的事情。

local.settings.json

   {
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "",
"Hello": "world"
 },
"ClientConfiguration": {
    "this": "that",
    "SubscriberEndpoint": "",
    "Username": "",
    "Password": "",
    "ObjectEndpoint": ""
 }
}

在我的代码中,我有

 var config = JsonConvert.DeserializeObject<myConnectionObject> (Environment.GetEnvironmentVariable("ClientConfiguration"));

无论我做什么,我都无法正常工作。为什么我至少不能获得ClientConfiguration的内容?只是不断返回null。

如果我将ClientConfiguration {}添加到

之类的值
..."Values" : { ... 
"Hello":"world",
"ClientCOnfiguration" : {above}
}

我最后遇到一条错误,说找不到azurewebjobsstorage,并且“功能设置列表”只是空的

3 个答案:

答案 0 :(得分:2)

对于local.settings.json,只能将Values部分导入到环境变量中。(如果您的函数是v2,则环境变量中也有ConnectionStrings部分)。因此,您会看到结果为null。

此外,Values部分是Dictionary<string, string>,这意味着值只能是字符串以外的其他格式。因此,您的ClientCOnfiguration内部错误导致出现。

由于您要重新组织这些设置,因此将ClientConfiguraiton序列化以将其存储在Values中似乎不是一个好选择。我们可能只需要读取和解析Json文件即可。

在函数方法签名中添加ExecutionContext context,然后尝试下面的代码。

var reader = new StreamReader(context.FunctionAppDirectory+"/local.settings.json");
var myJson = reader.ReadToEnd();
dynamic config =  JsonConvert.DeserializeObject(myJson);
var clientConfiguration = config.ClientConfiguration as JObject;
myConnectionObject mco = clientConfiguration.ToObject<myConnectionObject>();

如果您的函数是v2,则ConfigurationBuilder还有另一种方法。

var config = new ConfigurationBuilder()
    .SetBasePath(context.FunctionAppDirectory)
    .AddJsonFile("local.settings.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();
var mco = new myConnectionObject();
config.GetSection("ClientConfiguration").Bind(mco);

请注意,local.settings.json适用于本地开发人员,默认情况下不会上载到Azure。需要删除<CopyToPublishDirectory>Never</CopyToPublishDirectory>中的functionname.csproj

答案 1 :(得分:0)

据我所知,Values集合应该是一个Dictionary,如果它包含任何非字符串值,则可能导致Azure函数无法从local.settings.json中读取值。有关更多详细信息,请参阅blog

答案 2 :(得分:0)

如果您不想实例化新的ConfigurationBuilder,则可以简单地以其他方式格式化设置。您的local.settings.json文件如下所示:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "",
    "Hello": "world",
    "ClientConfiguration__this": "that",
    "ClientConfiguration__SubscriberEndpoint": "........",
    "ClientConfiguration__Username": "........",
    .....
 }
}

请注意,双下划线很重要,因为它指示环境变量读者将this当作复杂对象ClientConfiguration的属性。 您的自定义属性必须位于Values对象内部,否则它们将不会作为环境变量被注入。