I am using Azure Functions 2
I am going through Azure Function Local settings file documentation here:
https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local#local-settings-file
Per documentation, here is an example of local.settings.json file:
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "<language worker>",
"AzureWebJobsStorage": "<connection-string>",
"AzureWebJobsDashboard": "<connection-string>",
"MyBindingConnection": "<binding-connection-string>"
},
"Host": {
"LocalHttpPort": 7071,
"CORS": "*"
},
"ConnectionStrings": {
"SQLConnectionString": "<sqlclient-connection-string>"
}
}
I understand that the items in “Values” will be available through environment variables like Environment.GetEnvironmentVariable
I need to include more sophisticated settings ( nested JSON data with arrays in them) in my Function’s settings.
What would be the best practice or recommended practice to do that?
Values
collection is expected to be a Dictionary<string, string>
, therefore we can't put nested JSON data with arrays inside. Try to create a new section for your Json data and read Json file as usual. We can't use Environment.GetEnvironmentVariable
because the custom settings are not imported into environment variables.
{
"Values": {},
"CustomSettings":{}
}
Add ExecutionContext context
to function method signature to locate settings file.
var reader = new StreamReader(context.FunctionAppDirectory+"/local.settings.json");
var myJson = reader.ReadToEnd();
For v2 function, we can use ConfigurationBuilder
.
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
local.settings.json
is designed to provide local dev with an equivalent of Application settings in Azure portal, it's not published to Azure by default. To publish it, right click on project> Edit <functionappname>.csproj
and remove <CopyToPublishDirectory>Never</CopyToPublishDirectory>
.