Azure Function appsettings.json

In this comprehensive article, I’ll walk you through everything you need to know about using appsettings.json in Azure Functions – from basic setup to advanced patterns that I’ve implemented for my clients.

Azure Function appsettings.json

One important thing to note is that Appsettings.json has already been deprecated for a long time. That was the old name for the local.settings.json file. The new file is the local.settings.json file now. All the configurations for the Azure Functions.

Why Use appsettings.json in Azure Functions?

Before diving into implementation details, let’s understand why appsettings.json is so valuable for Azure Functions:

  • Familiar pattern: If you’re coming from ASP.NET Core, you already know how it works
  • Hierarchical configuration: Organize complex settings in nested structures
  • Environment-specific overrides: Easily manage different settings across dev, test, and production
  • Strongly-typed configuration: Bind configuration sections to C# classes

Adding appsettings.json to your Function App

Let’s start with the basics. Here’s how I set up appsettings.json in a new Azure Function project:

Step 1: Create the appsettings.json File

First, add an appsettings.json File to your function project root. I typically start with something like:

{
  "ConnectionStrings": {
    "SqlDatabase": "Server=myserver.database.windows.net;Database=mydb;User ID=admin;Password=securePassword;"
  },
  "AzureStorage": {
    "BlobContainerName": "documents",
    "QueueName": "processing-queue"
  },
  "ApplicationSettings": {
    "MaxRetryAttempts": 3,
    "ProcessingTimeoutInSeconds": 120
  }
}

Step 2: Configure Your Function App to Use appsettings.json

For .NET Functions, you need to modify your Program.cs or startup code. In a .NET isolated process function (recommended for new projects in 2024), your Program.cs should look like below:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWorkerDefaults()
    .ConfigureAppConfiguration(config =>
    {
        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        config.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT")}.json", optional: true, reloadOnChange: true);
        config.AddEnvironmentVariables();
    })
    .Build();

host.Run();

For in-process functions, you’d add a Startup.cs Class:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]
namespace MyNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT")}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables()
                .Build();

            builder.Services.AddSingleton<IConfiguration>(configuration);
        }
    }
}

Step 3: Mark appsettings.json as Content in Project File

To ensure the file is copied to the output directory, add this to your .csproj file:

<ItemGroup>
  <None Update="appsettings.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
  <None Update="appsettings.Development.json">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

Using Configuration in Your Functions

Now that it’s set up, let’s see how to access the configuration in your function code.

Method 1: Using IConfiguration Directly

The most straightforward approach is to inject IConfiguration into your function method:

public class MyFunctions
{
    private readonly IConfiguration _configuration;

    public MyFunctions(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [Function("ProcessOrder")]
    public async Task ProcessOrder([QueueTrigger("orders")] string orderMessage)
    {
        // Access configuration directly
        string connectionString = _configuration.GetConnectionString("SqlDatabase");
        int maxRetries = _configuration.GetValue<int>("ApplicationSettings:MaxRetryAttempts");
        
        // Function logic here
    }
}

Method 2: Using Strongly-Typed Configuration

// Define configuration classes
public class ApplicationSettings
{
    public int MaxRetryAttempts { get; set; }
    public int ProcessingTimeoutInSeconds { get; set; }
}

public class AzureStorageSettings
{
    public string BlobContainerName { get; set; }
    public string QueueName { get; set; }
}

// In Startup.cs or Program.cs
services.Configure<ApplicationSettings>(configuration.GetSection("ApplicationSettings"));
services.Configure<AzureStorageSettings>(configuration.GetSection("AzureStorage"));

// In your function
public class MyFunctions
{
    private readonly ApplicationSettings _appSettings;
    private readonly AzureStorageSettings _storageSettings;

    public MyFunctions(
        IOptions<ApplicationSettings> appSettings,
        IOptions<AzureStorageSettings> storageSettings)
    {
        _appSettings = appSettings.Value;
        _storageSettings = storageSettings.Value;
    }

    [Function("ProcessDocument")]
    public async Task ProcessDocument([BlobTrigger("documents/{name}")] Stream document)
    {
        // Use strongly-typed settings
        int timeout = _appSettings.ProcessingTimeoutInSeconds;
        string queueName = _storageSettings.QueueName;
        
        // Function logic here
    }
}

Environment-Specific Configuration

One major advantage of appsettings.json is handling different environments. Here’s my approach:

Creating Environment-Specific Files

I create multiple files like:

  • appsettings.json – Base settings
  • appsettings.Development.json – Local development overrides
  • appsettings.Production.json – Production settings

    For example, my development file might look like:

    {
      "ConnectionStrings": {
        "SqlDatabase": "Server=localhost;Database=devdb;Integrated Security=true;"
      },
      "ApplicationSettings": {
        "MaxRetryAttempts": 10,
        "ProcessingTimeoutInSeconds": 300
      }
    }
    

    Handling Environment Variables in Azure

    In the Azure portal, I set the AZURE_FUNCTIONS_ENVIRONMENT application setting to the current environment name (e.g., “Production”). This ensures the correct file is loaded.

    Advanced Configuration Patterns

    After working with large enterprises like Contoso Financial in New York and TechGiant in Seattle, I’ve developed some advanced patterns:

    Pattern 1: Configuration Validation

    Validate configuration at startup to fail fast if settings are missing:

    public class ApplicationSettings
    {
        public int MaxRetryAttempts { get; set; }
        public int ProcessingTimeoutInSeconds { get; set; }
        
        public void Validate()
        {
            if (MaxRetryAttempts <= 0)
                throw new ArgumentException("MaxRetryAttempts must be positive");
            
            if (ProcessingTimeoutInSeconds <= 0)
                throw new ArgumentException("ProcessingTimeoutInSeconds must be positive");
        }
    }
    
    // In Startup
    var appSettings = new ApplicationSettings();
    configuration.GetSection("ApplicationSettings").Bind(appSettings);
    appSettings.Validate();
    services.AddSingleton(appSettings);
    

    Pattern 2: Secrets Management

    For sensitive data, I use Azure Key Vault instead of storing secrets in appsettings.json:

    // In Program.cs
    .ConfigureAppConfiguration((context, config) =>
    {
        var builtConfig = config.Build();
        var keyVaultEndpoint = builtConfig["KeyVault:Endpoint"];
        
        if (!string.IsNullOrEmpty(keyVaultEndpoint))
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var keyVaultClient = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(
                    azureServiceTokenProvider.KeyVaultTokenCallback));
                    
            config.AddAzureKeyVault(
                keyVaultEndpoint,
                keyVaultClient,
                new DefaultKeyVaultSecretManager());
        }
    })
    

    Pattern 3: Configuration Reloading

    For long-running functions that should pick up configuration changes:

    public class ReloadableSettings
    {
        private readonly IOptionsMonitor<ApplicationSettings> _settings;
        
        public ReloadableSettings(IOptionsMonitor<ApplicationSettings> settings)
        {
            _settings = settings;
        }
        
        public int GetMaxRetries() => _settings.CurrentValue.MaxRetryAttempts;
    }
    

    Manage Application Settings for Azure Functions within Visual Studio

    When working with the Azure Function, if you want to add, edit, or delete any of the application settings. We normally log in to the Azure Portal and navigate to our Azure function app, and then from the Application settings section, we use it to perform all the operations as shown below.

    azure function app settings visual studio

    But there is another way to Manage the Application settings from Visual Studio itself. As you can see from the screenshot below, we can click on the Edit Azure App Service settings link.

    azure function appsettings.json

    If you click on the + Add Setting, you can see the window below to add the App settings.

    azure functions appsettings.json

    Best Practices

    Below are the best practices:

    1. Combine approaches: Use appsettings.json for structured configuration and Azure App Settings for environment-specific values and secrets
    2. Use strongly-typed configuration: Always bind to POCO classes for better

    You may also like the following articles below

    Azure Virtual Machine

    DOWNLOAD FREE AZURE VIRTUAL MACHINE PDF

    Download our free 25+ page Azure Virtual Machine guide and master cloud deployment today!