C# 将数据库连接字符串从appconfig.json迁移到环境变量

C# 将数据库连接字符串从appconfig.json迁移到环境变量,c#,azure,asp.net-core,environment-variables,asp.net-core-webapi,C#,Azure,Asp.net Core,Environment Variables,Asp.net Core Webapi,我有一个.NET5WebAPI作为Azure应用程序服务托管。 该应用程序连接到MySql数据库,该数据库也托管在Azure上(Azure数据库用于MySql服务器) 到目前为止,我在代码的appsettings.json文件中已经有了MySql数据库的连接字符串。 我想把它移到一个环境变量。(我知道Azure Key Vault,但我在试图弄清楚这一点时有点迷茫,所以我想我应该尝试使用环境变量) 目前,我正在我的开发PC(Windows10+VisualStudioCommunity2019)

我有一个.NET5WebAPI作为Azure应用程序服务托管。 该应用程序连接到MySql数据库,该数据库也托管在Azure上(Azure数据库用于MySql服务器)

到目前为止,我在代码的appsettings.json文件中已经有了MySql数据库的连接字符串。 我想把它移到一个环境变量。(我知道Azure Key Vault,但我在试图弄清楚这一点时有点迷茫,所以我想我应该尝试使用环境变量)

目前,我正在我的开发PC(Windows10+VisualStudioCommunity2019)上本地测试此功能。一旦我在那里工作,我也会在生产环境上做同样的事情

如前所述,MySql数据库的连接字符串当前存储在appsettings.json文件中,如下所示:

"ConnectionStrings": {
    "MyDataContext": "Server=abc.mysql.database.azure.com;user id=someuser@abc;Pwd=somepassword;persistsecurityinfo=True;database=somedatabase;TreatTinyAsBoolean=false"
  },
因此,我在我的开发机器上创建了一个名为ConnectionStrings\uuuu MyDataContext的系统变量。 然后,我从appsettings.json中删除了上述行,以确保我的应用程序不再从那里读取内容

但是现在我有点迷路了。。。我想也许这就是我所需要做的,就像我的Program.cs,它看起来是这样的:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        })
   .UseNLog();
}
services.AddDbContext<LogContext>(options =>
    options.UseMySql(Configuration.GetConnectionString("MyDataContext"), new MySqlServerVersion(new Version(5, 7, 29))));
公共静态IHostBuilder CreateHostBuilder(字符串[]args)=>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder=>
{
webBuilder.UseStartup();
})
.ConfigureLogging(日志=>
{
logging.ClearProviders();
logging.AddConsole();
logging.AddDebug();
logging.addeventsourceloger();
logging.SetMinimumLevel(Microsoft.Extensions.logging.LogLevel.Trace);
})
.UseNLog();
}
包含CreateDefaultBuilder(),根据Microsoft文档,“从环境变量加载应用程序IConfiguration”。但是,在my Startup.cs中:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddDbContext<MyContext>(options =>
        options.UseMySql(Configuration.GetConnectionString("MyDataContext"), new MySqlServerVersion(new Version(5, 7, 29))));
    ...
}
public void配置服务(IServiceCollection服务)
{
...
services.AddDbContext(选项=>
使用MySQL(Configuration.GetConnectionString(“MyDataContext”)、新的MySqlServerVersion(新版本(5,7,29));
...
}
GetConnectionString(“MyDataContext”)返回null

我还尝试将连接字符串作为用户变量而不是环境变量添加,但这没有什么区别

我还需要做些什么来让它工作吗? 我还没有在生产环境中尝试过这一点——我想先让它在我的开发机器上运行

谢谢

请尝试使用来指定
连接字符串\uuu MyDataContext

{
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:64645",
      "sslPort": 44366
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "ConnStringInEnv": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ConnectionStrings__MyDataContext": "Server=abc.mysql.database.azure.com;user id=someuser@abc;Pwd=somepassword;persistsecurityinfo=True;database=somedatabase;TreatTinyAsBoolean=false"
      }
    }
  }
}

好的,唯一的问题是我在调试模式下运行WebAPI(在VisualStudio中)。一旦发布到Azure应用程序服务,它就可以工作了。重述:

在Azure应用程序服务配置中,我添加了一个名为ConnectionString\uuuMyDataContext的环境变量,该变量具有相关值

在我的代码的Startup.ConfigureServices()方法中,我读入环境变量并赋值,如下所示:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        })
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();
            logging.AddDebug();
            logging.AddEventSourceLogger();
            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        })
   .UseNLog();
}
services.AddDbContext<LogContext>(options =>
    options.UseMySql(Configuration.GetConnectionString("MyDataContext"), new MySqlServerVersion(new Version(5, 7, 29))));
services.AddDbContext(选项=>
使用MySQL(Configuration.GetConnectionString(“MyDataContext”)、新的MySqlServerVersion(新版本(5,7,29));

就这样

配置配置时,您在哪里添加了环境变量?您可以在azure portal中配置连接字符串,因此只需在appconfig.json中保留空的连接字符串值,如果在
启动
中使用了
配置
,将替换连接字符串注入到手动构建中?@Nkosi感谢您的回复。不幸的是,我不太明白你的问题。因此,我在我的开发PC上的Windows中添加了一个环境变量(因为我想先让它在本地工作)。我还将其添加到Azure应用程序服务中(在配置->应用程序设置下),至于生产,我想我也需要它。我想我只是不知道如何读取这些环境变量。我有点认为它会自动发生。@FabricioRodriguez默认的env变量前缀是
DOTNET\uu
ASPNETCORE\u
。您是否尝试过
DOTNET\u连接字符串\uuuu MyDataContext
ASPNETCORE\u连接字符串\uuu MyDataContext