Accessing Connection String values in Azure Function V1 and V2

Connection string is a good way to store database or source system connection string. Currently Azure Function provides four different types on connection strings as below.

  1. MySql- Conection string for MySql database
  2. SQLServer- Connection strings for SQL server
  3. SQLAzure – Connection strings for SQL Azure
  4. Custom—Any other types of connection string excluding above

The way for accessing Connection string is different in V1 and V2 as V2 is does not support configuration manager.

Accessing Connection string in Azure function V1

Below are the steps for accessing connection string in azure function v1 .

  1. Add nuget package “Configuration.ConfigurationManager
  2. Add the namespace “System.Configuration
  3. Then access connection string as below
var connectionString = ConfigurationManager.ConnectionStrings[“CRM_CONNECTION_STRING”].ConnectionString;

While running the code from azure app service create the connection as custom connection string

The sample code could be found on GitHub

 Accessing Connection string in Azure function V2

Unlike azure function 1.x azure function 2.x does not support configuration manager. So, the process for accessing the connection string is different. Below are the steps for that

  1. Add the namespace “Extensions.Configuration
  2. Add a third parameter in the function Run method of type ExecutionContext
public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, “get”, “post”, Route = null)]HttpRequest req, ILogger log, ExecutionContext context)
  1. Add the following code in the beginning of the function
var config = new ConfigurationBuilder()

.SetBasePath(context.FunctionAppDirectory)

.AddJsonFile(“local.settings.json”, optional: true, reloadOnChange: true)

.AddEnvironmentVariables()

.Build();

For a local run this code will get application settings and connection string from local.settings.json and for a deployment this code this take the environment variables from appsettings and connection string from the app service.

  1. Access Connection String as below
var connectionString = config.GetConnectionString(“CRM_CONNECTION_STRING”);
  1. Access app settings as below
var setting1 = config[“Settings1”];

The sample code can be found on GitHub

 

 

 

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s