EF Core connection string settings with azure functions and web api

asp.net-core azure azure-functions c# entity-framework-core

Question

I have 2 projects 1.ASP.NET Core WEB API 2. Azure function

Both are hosted on a azure. I also have different accounts for development and production, hense I need to have different connection strings depending on environment the application are deployed on.

For entity framework I use a separate project which the 2 application refer to.

Whene the separate project is used from weba api I can read a connection string this way

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        IConfigurationRoot configuration = new ConfigurationBuilder()
                                            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))

            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile($"appsettings.{envName}.json", optional: false)
            .Build();

        var cs = configuration.GetConnectionString("DefaultConnection");
        optionsBuilder.UseSqlServer(cs);
    }
}

But there's no appsettings.json file for trigger. What can I do in this case?

1
1
9/4/2019 9:58:56 AM

Accepted Answer

For Local Development use an Environment Variable to store your connection string. (Right click your Azure Function Project in Visual Studio select properties, Debug and you will be able to add an Environment Variable there. This will be stored in launchsettings.json) For example you could call it MSSQL_CONN_STR

When Deployed to Azure use Application Settings (Goto Function app click Configuration and you can add a new Application Setting/Environment variable with the same key as above (MSSQL_CONN_STR) but with your production value for the connection string)

In your C# code you can get the Environment Variable the same as you have above

Environment.GetEnvironmentVariable("MSSQL_CONN_STR");

From MS regarding Application Settings for Azure Function App

Application Settings are exposed as environment variables for access by your application at runtime

1
9/4/2019 11:24:58 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow