Azure — Reading application settings in Azure Functions (ASP.NET Core)
Reading settings from Azure Functions in .NET.
For the second (v2) and third (v3) generation of Azure Functions, the logic changes a bit. Not quite as straightforward, but more flexible. ConfigurationManager is not used anymore. Instead, you’re supposed to use ConfigurationBuilder. OR
Just like any other .NET application, Azure Functions can also read app settings by using the System.Environment.GetEnvironmentVariable
method.
Recommended way — use environment variable to read settings.
var value = Environment.GetEnvironmentVariable("your_key_here");
The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values.
For local, app settings are defined in the local.settings.json
file which is only for local development use, even though it is already obvious by the name of it. However, I found a lot of developers still mistakenly think settings defined here would take effect in Azure — the answer is absolutely not. To add a custom setting to your local.settings.json simply add a new entry in Values
.
// local.settings.json
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"MyCustomSetting":"a custom setting"
}
}
FunctionAppDirectory sets the directory to find your local.settings.json file. Set
optional
to true because we won’t have the file when we deploy. AddEnvironmentVariables will pick up both App Settings and Connection Strings from Azure settings.
using Microsoft.Extensions.Configuration;public static void Run(TimerInfo myTimer, ILogger log)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();var appSettingValue = config["appSettingKey"];var connection = config.GetConnectionString("SqlConnectionString");
}
Run in Azure
View more from Awesome Azure
- Difference between Traffic Manager and Front Door Service
- Difference between Azure Load Balancer and Application Gateway
- Difference between Azure Private Links and Azure Service Endpoints
- Difference between Azure Blob Storage and Azure Data Lake Storage (ADLS)
- Difference between Azure SQL Database and Azure SQL Managed Instance
- Difference between Azure Storage Queue and Service Bus Queue
Happy Clouding!!!