Get Connection String in Azure Function v3
Asked Answered
T

4

17

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?

Tutelary answered 16/6, 2020 at 10:9 Comment(0)
A
16

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

Environment.GetEnvironmentVariable("CUSTOMCONNSTR_DefaultConnection");
Aton answered 16/6, 2020 at 11:30 Comment(2)
This prefix classification is: CUSTOMCONNSTR_ => Custom provider; MYSQLCONNSTR_ => MySQL; SQLAZURECONNSTR_ => Azure SQL Database; SQLCONNSTR_ => Sql Server;Trask
How one is supposed to write the function code to get connection string in both dev and azure enviornment?Peony
I
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.

Izzy answered 16/6, 2020 at 11:12 Comment(1)
This is what I would rather like to avoid, I think it's cleaner to put it into connection strings, but thanks anywayTutelary
B
5

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"
  }
}
Brunn answered 1/4, 2021 at 12:55 Comment(0)
L
2

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;
        }
Leatherwood answered 20/7, 2023 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.