Search code examples
azureasp.net-coreentity-framework-6.net-6.0azure-appservice

Dummy Connection String Stopped Working When the Azure Web App was Migrated to .Net 6


We have a Web Api 2 application that is using .Net Framework 4.6.1. Since we don't want our connection string to be exposed, the app has a dummy connection string in web.config when deployed to Azure App Service. enter image description here

That dummy connection string is being overridden by the connection string in Azure App Service Configuration. See this article: https://mohitgoyal.co/2017/07/05/update-connection-string-for-entity-framework-in-azure-web-app-settings/

It stopped working when we migrated to Asp.Net Core using .Net 6. I have tried moving it to app.config but it still doesn't work.

We are still using Entity Framework 6 on .Net 6 and the connection string is being referenced in the constructor.

    public AppDBContext() : base("name=AppDBContext")
    {
    }

This is why we need to have our connection string in a config xml file rather than in the appsettings.json.

My questions are:

  • Shouldn't azure app service treat app.config the same way it treats web.config?
  • Should we change the way we reference the connection string so that we can read from the Azure AppService Configuration?

Solution

  • When we create Asp. Net Core Web App using .Net 6, appsettings.json file will be created.

    Add your Connection String in appsettings.json

    My appsettings.json

    {
      "ConnectionStrings": {
        "DefaultConnection": "Your Connection String"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*"
    }
    

    enter image description here

    My Program.cs

    var builder = WebApplication.CreateBuilder(args);
    string connString = builder.Configuration.GetConnectionString("DefaultConnection");
    

    Shouldn't azure app service treat app.config the same way it treats web.config?

    app.config is available in Console and Windows applications, whereas .NET Core Applications will have appsettings.json file to store connection strings and other Environment Variables.

    The setting in appsettings.json will be overrided by Environment variables added in Azure App Settings .

    Make sure your Connection String name in Azure App settings is same as in appsettings.json file.

    Connection String in Azure App Settings enter image description here