Introduction
Generally, we define configuration based key values in application settings files. In Azure Functions, you can define your settings in local.settings.json file.
local.settings.json
Values defined in local.settings.json are specific to your local development and are not copied when you publish to Azure. Now lets add a custom settings to local setting file.
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"appsettingkey": "dotnetmirror"
}
}
Read the setting using environment variable
Using simple one liner code, you can read the setting value using Environment.GetEnvironmentVariable method. This is easy and recommended way.
string value = Environment.GetEnvironmentVariable("appsettingkey");
Read the setting using Microsoft.Extensions.Configuration
Add Microsoft.Extensions.Configuration Nuget package to your azure function project and using below code, you should be able to read the settings value.
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
string value = config["appsettingkey"];
Deploy to Azure
Once you deploy your Function App to Azure, your settings will not work directly. You must add the settings(appsettingkey) to Application setting under Configuration.
Fig 1 - Add Application Settings in Azure
Read using System.Configuration
You can not use ConfigurationManager to read app settings from Azure Functions V2 and above versoins. If you try to use Configuration Manager, you will get below error.
Fig 2 - Read AppSettings using ConfigurationManager throws error
Function1.cs
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using System;
namespace DotNetMirror
{
public static class ReadFunctionAppSettings
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log, ExecutionContext context)
{
try
{
//read using ConfigurationManager from System.Configuration
//string response = ConfigurationManager.AppSettings["appsettingkey"].ToString();
//read using Microsoft.Extensions.Configuration
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
string value = config["appsettingkey"];
//read using Microsoft.Extensions.Configuration
value = Environment.GetEnvironmentVariable("appsettingkey");
return new OkObjectResult(value);
}
catch(Exception ex)
{
log.LogError(ex.Message);
}
return null;
}
}
}