Home > Mobile >  How does "Connection strings" work in Azure App Service Configuration?
How does "Connection strings" work in Azure App Service Configuration?

Time:06-01

I have .NET 6 app which is hosted in Azure, it is run on Linux. I just created App Service and publish there my app from Visual studio. This app is connected to MS SQL server in Azure.

At first I put connection string into appsettings.json file. Then I wanted to do that in more true way. In the end I found possibility to set connection string into Configuration inside my App Service. There is even special section in Configuration, called "Connection strings".

So, I placed connection string there, remove it from appsettings.json, republish my app and even restart it then in Azure. It seems, app works fine.

It became interesting to me how this connection string is got into my app. I noticed that into container with my app appeared environment variable SQLAZURECONNSTR_MondayDbContext with my connection string.

I tried to do the same locally on my Windows 10. I set environment variable SQLAZURECONNSTR_MondayDbContext and even SQLAZURECONNSTR__MondayDbContext but app is crashed. I also tried set this through command line argument, but the same, app doesn't see connection string.

How does it work in Azure?

CodePudding user response:

How does "Connection strings" work in Azure App Service Configuration?

  • Setting connection strings in App Service are like setting them as <connectionStrings> in Web.config, the values you set in App Service override the ones in Web.config.

  • You can keep development settings in Web.config and production secrets safely in App Service.

  • The same code uses your development settings when you debug locally, and it uses your production secrets when deployed to Azure.

  • The key name in the Azure app Configuration has to be same as the key name in the local configuration settings.

  • When you have connectionstring in both azure application Setting and web.config, the azure settings will override web.config. You need to set key/value in web.config when you test in local.

  • A connection string added in Configuration section of the App Service with the name of "DefaultConnection" will look like SQLCONNSTR_DefaultConnection in the environment variables.

  • To access it in code ,use

configuration.GetConnectionString("DefaultConnection")

CodePudding user response:

I figured out with this. It turns out this works only when you set this variable through environment variable. This is because EnvironmentVariablesConfigurationProvider is aware of this and some other prefixes: MYSQLCONNSTR_, SQLAZURECONNSTR_, SQLCONNSTR_, CUSTOMCONNSTR_. If you set any environment variable with this prefix you can get them from Configuration as if they were set to ConnectionStrings section.

  • Related