I know i could add all my environment vars under the values {} section of local.settings.json. I am however trying to keep a tidy home and would like if I could do something like this.
local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "",
"Hello": "world"
},
"ClientConfiguration": {
"this": "that",
"SubscriberEndpoint": "",
"Username": "",
"Password": "",
"ObjectEndpoint": ""
}
}
in my code i have
var config = JsonConvert.DeserializeObject<myConnectionObject> (Environment.GetEnvironmentVariable("ClientConfiguration"));
No matter what I do I cannot get this to work. Why can't I at least get the contents of ClientConfiguration? Just keeps coming back null.
IF I add ClientConfiguration {} to the values like
..."Values" : { ...
"Hello":"world",
"ClientCOnfiguration" : {above}
}
I end up with an error saying azurewebjobsstorage can't be found and 'func settings list' is just empty
For local.settings.json, only Values section can be imported into Environment variables.(If your function is v2, ConnectionStrings section is also there in Environment variables). So you see null as the result.
What's more, Values section is a Dictionary<string, string> which means value can't be in other format except string. Hence your ClientCOnfiguration inside results in error .
Since you want to reorganize those settings, serializing ClientConfiguraiton to store it in Values seems not a good option. We may need simply reading and parsing Json file.
Add ExecutionContext context in your function method signature and try code below.
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>();
If your function is v2, there's another way with 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);
Note that local.settings.json is for local dev, it won't be uploaded to Azure by default. Need to remove <CopyToPublishDirectory>Never</CopyToPublishDirectory> in functionname.csproj.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With