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.
- MySql- Conection string for MySql database
- SQLServer- Connection strings for SQL server
- SQLAzure – Connection strings for SQL Azure
- 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 .
- Add nuget package “Configuration.ConfigurationManager”
- Add the namespace “System.Configuration”
- 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
- Add the namespace “Extensions.Configuration”
- 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)|
- Add the following code in the beginning of the function
|var config = new ConfigurationBuilder()
.AddJsonFile(“local.settings.json”, optional: true, reloadOnChange: true)
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.
- Access Connection String as below
|var connectionString = config.GetConnectionString(“CRM_CONNECTION_STRING”);|
- Access app settings as below
|var setting1 = config[“Settings1”];|
The sample code can be found on GitHub