I have an ASP.NET Core app deployed in Azure App Service, with both staging and production deployment slots. Currently, the app uses a single Azure SQL Database connection string stored in Azure Key Vault.
In my Program.cs
file, I retrieve the connection string as follows:
var sqlConnectionString = builder.Configuration.GetSection("sqlConnectionString").Value;
builder.Services.AddDbContext<MyAppContext>(options =>
options.UseSqlServer(sqlConnectionString ?? throw new InvalidOperationException("Connection string 'MyAppContext' not found.")));
The sqlConnectionString is not stored in appsettings.json
; it is fetched directly from the Key Vault.
I need to connect the production deployment slot to a different Azure SQL Database. This should ensure that when I swap slots, the production instance of the app connects to the production database.
I added a new Connection String
named sqlConnectionString
of type SQLAzure
under the Environment Variables
in the production slot settings. However, this did not work, and the production slot still connects to the staging database.
2
Answers
In
Program.cs
I added the following code:In development mode, I get the connection string from Key Vault using the
GetSection
method. In staging and production modes, I get the connection string using theGetConnectionString
method.Additionally, I made the following improvements in Azure App Service:
sqlConnectionString
to the Connection Strings section for both the Production and Staging deployment slots.ASPNETCORE_ENVIRONMENT
in both the staging and production environments. For the staging environment, the value is set toStaging
, and for the production environment, the value is set toProduction
.As a result, my development and staging environments are now connected to one database, while the production environment is connected to a separate production database.
When you create a new slot. You will get Environment variable option to add new
App settings or Connection string
for the slot, as shown below:To stop changes for a app settings/ To separate app setting for particular slot setting, use the option
Deployment slot setting
For reference check this MSDocs.
I am fetching a simple value application setting value in different slots.
without enabling the
Deployment slot setting
OUTPUT
:Before Swap :-
production slot
staging slot
when you swap you can see all the slot settings enable values are available during swap. when you do not enable the
Deployment Slot Setting
After Swap :-
production slot
After enabling the
Deployment slot setting
As you can see now
sql_conn
settings are not available in option duringslot swap
because that app setting is fixed for the slots.