azureasp.net-coreasp.net-core-webapiazure-app-api

Storing connection strings in Azure App Service Settings


I have an ASP .Net Core 2.2 Web API which connects to a MySQL Database. It is hosted on Azure App Service.

Currently I am storing the connection strings in the appsettings.json file:

"ConnectionStrings": {
    "MyDataContext": "Server=server1.mysql.database.azure.com;user id=username;Pwd=password;persistsecurityinfo=True;database=db1;"
  }

And I read the connection strings in Startup.cs (in the ConfigureServices method) like this:

services.AddDbContext<MyContext>(options => options.UseMySql(Configuration.GetConnectionString("MyDataContext")));

I read that I can store these connection strings in the Azure App Service Settings instead, as it offers some advantages. I've been trying to do this, but am struggling to get it to work.

My first question is, when adding the connection string to Azure App Service Settings (under the Connection Strings section), what do I put in for Name in the Name/Value pairs? Do I just put "MyDataContext" or do I put in "ConnectionStrings:MyDataContext"? (I'm trying to keep the same structure as I have in the appsettings.json file). My second question is, can I still read the connections string in my Startup.ConfigureServices method the same way I am doing now? From what I understand, Azure App Service will automatically inject the connection string store in Settings into the Configuration object in the API? I'm not sure if I'm missing something, but it's not working...

enter image description here


Solution

  • Yes and yes.

    Yes, you can name the connection string as almost anything you want, though I've discovered recently that certain characters aren't allowed, but Azure doesn't tell you this, it will just strip them out and not tell you, so to be safe I'd only use alphanumeric characters, you can use CamelCasing if you need to. You don't need to prefix with anything like ConnectionStrings: as this is done automatically by Azure, and the syntax has changed in the most recent version anyway.

    And yes, if you haven't specified your own ConfigurationBuilder, your web app should call CreateDefaultBuilder which will add environment variables at runtime. The code you've written will stay the same and you can delete the connection string from your appsettings.json file, if you keep it in there it will get overridden anyway.

    It is a good idea to remove connection strings from the appsettings.json file if you are able to store them in Azure instead for security reasons, so that you are not storing either database server address nor connection credentials in your source code. One step up from this is using Managed Identity in conjunction with Active Directory, where you specify an AD username in the connection string but no password, then assign that user (or the user's group) as the server admin.