Azure Environment Variables

Azure Environment Variables 

(such as DB Connection string)


.NET 6.0+ can read from the Azure environment variables.

Especially useful for database connection strings for Azure databases for development vs. testing vs. staging vs. production, rather than hard-coding them.


Old way:

   var connectionString = _configuration.GetConnectionString("ApiConnectionAzure");

and in appsettings.Development.json

"ConnectionStrings": {
    "ApiConnectionAzure": "some DB-Connection-String-Dev-Encrypted#"
  }

New way:

In your Azure portal ( https://portal.azure.com/  ), click on your server.

Then click "Settings" > "Environment Variables" > "Connection Strings" tab > look at list of your created environment variables. Add if missing.  Remember the name.

In your code the ContextFactory should be, 

public APIContext CreateConnectionAzure()

{

    // NOTE - "MyEnvironmentVariableName" is defined on https://portal.azure.com/ in the Environment variables

    //  under the server. This string is not in any defined appsettings.json file.

    var connectionString = _configuration.GetConnectionString("MyEnvironmentVariableName");

    var options = new DbContextOptionsBuilder<APIContext>().UseSqlServer(connectionString).Options;

    return new APIContext(options);

}





Comments

Popular posts from this blog

Upgrading to .NET8 from desktop versions 4.8.X

GHL Chat Bots for Webpage

GHL > Set website so shorter URL address