12

I am very confused. I want to get a connection string in an Azure v3 function (.Net Core 3.1).

My local settings looks like

{
    "IsEncrypted": false,
    "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
    },
    "ConnectionStrings": {
      "DefaultConnection": "bla bla"
    }
}

and in the function I do

string defaultConnection = Environment.GetEnvironmentVariable("ConnectionStrings:DefaultConnection");

This works fine locally but on Azure, defaultConnection is null. I defined the connection under the section Connection strings of the function's Application Settings.

enter image description here

Is my approach correct for Azure function v3?

AGuyCalledGerald
  • 7,882
  • 17
  • 73
  • 120

4 Answers4

14

You need the specify the connection string prefix (see documentation):

Environment.GetEnvironmentVariable("CUSTOMCONNSTR_DefaultConnection");
Philip
  • 3,135
  • 2
  • 29
  • 43
  • 4
    This prefix classification is: CUSTOMCONNSTR_ => Custom provider; MYSQLCONNSTR_ => MySQL; SQLAZURECONNSTR_ => Azure SQL Database; SQLCONNSTR_ => Sql Server; – Freddy Guerrero Feb 05 '21 at 21:43
  • 12
    How one is supposed to write the function code to get connection string in both dev and azure enviornment? – Francesco Mar 27 '21 at 18:59
5

Please note that

Connection strings should only be used with a function app if you are using entity framework. For other scenarios use App Settings.

So if you just want to get the value of DefaultConnection, you can put it under Application settings and you can get it like this

Environment.GetEnvironmentVariable("DefaultConnection");

For Azure function with Entity Framework, please refer to this article.

Tony Ju
  • 14,891
  • 3
  • 17
  • 31
4

If you're using Microsoft.NET.Sdk.Functions 3.0.11 and Microsoft.Azure.Functions.Extensions 1.1.0 and you're using Azure Functions with Dependency Injection, you can do the following to access the connection string (or any configuration) when you start the application.

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

[assembly: FunctionsStartup(typeof(YourNamespace.Startup))]

namespace YourNamespace
{
    public class Startup : FunctionsStartup
    {
        public IConfiguration Configuration { get; set;  }

        public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
        {
            var config = builder.ConfigurationBuilder.Build();

            // This can be used to get a connection string from local.settings.json and also works when deployed to Azure
            var appConfigConnection = config.GetConnectionString("AppConfig");
            // This is to access the environment variables. 
            var environment = Environment.GetEnvironmentVariable("Environment");

            // This particular example uses the values retrieved to bootstrap Azure App Configuration
            builder.ConfigurationBuilder.AddAzureAppConfiguration(options =>
            {
                options.Connect(appConfigConnection).Select(KeyFilter.Any, environment.ToLowerInvariant());
            });
        }

        public override void Configure(IFunctionsHostBuilder builder)
        {
            // In case you need to access IConfiguration
            Configuration = builder.GetContext().Configuration;
        }
    }
}

Sample local.setting.json

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "AzureWebJobsStorage": "your connection string",
    "Environment": "Development"
  },  
  "ConnectionStrings": {
    "AppConfig": "your connection string"
  }
}
lopezbertoni
  • 3,551
  • 3
  • 37
  • 53
0

This is nasty but I think the only solution if you want to test locally and deploy the same code to Azure.

private string GetConnectionString(string connectionName)
        {
            // This should work locally
            string connectionString = Environment.GetEnvironmentVariable($"ConnectionStrings:{connectionName}");
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                // This should work in Azure
                connectionString = Environment.GetEnvironmentVariable($"SQLAZURECONNSTR_{connectionName}");
            }
            return connectionString;
        }
Phil
  • 951
  • 12
  • 16