【问题标题】:Migrating database connection string from appconfig.json to Environment Variable将数据库连接字符串从 appconfig.json 迁移到环境变量
【发布时间】:2021-04-16 09:37:18
【问题描述】:

我有一个作为 Azure 应用服务托管的 .Net 5 Web API。 该应用连接到同样托管在 Azure(Azure Database for MySQL 服务器)上的 MySql 数据库。

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

目前,我正在我的开发 PC(Windows 10 + Visual Studio Community 2019)上进行本地测试。一旦我让它在那里工作,我将在生产环境中做同样的事情。

所以就像我提到的,目前 MySql 数据库的连接字符串存储在 appsettings.json 文件中,如下所示:

"ConnectionStrings": {
    "MyDataContext": "Server=abc.mysql.database.azure.com;user id=someuser@abc;Pwd=somepassword;persistsecurityinfo=True;database=somedatabase;TreatTinyAsBoolean=false"
  },

所以我在我的开发机器上创建了一个名为 ConnectionStrings__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();
}

包含 CreateDefaultBuilder(),根据 Microsoft 文档,“从环境变量加载应用程序 IConfiguration”。但是,在我的 Startup.cs 中:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddDbContext<MyContext>(options =>
        options.UseMySql(Configuration.GetConnectionString("MyDataContext"), new MySqlServerVersion(new Version(5, 7, 29))));
    ...
}

Configuration.GetConnectionString("MyDataContext") 返回 null。

我也尝试将连接字符串添加为用户变量而不是环境变量,但这没有任何区别。

我还需要做些什么才能使其正常工作吗? 我还没有在生产环境中尝试过这个——我想先让它在我的开发机器上运行。

谢谢

【问题讨论】:

  • 配置配置的时候在哪里添加了环境变量?
  • 您可以在azure门户中配置您的连接字符串,因此您只需在appconfig.json中将连接字符串值留空,连接字符串将被替换docs.microsoft.com/en-us/azure/app-service/…
  • Configuration 中使用的Startup 是否注入手动构建?
  • @Nkosi 感谢您的回复。不幸的是,我不太明白你的问题。所以我在我的开发PC上向Windows添加了一个环境变量(因为我想让它首先在本地工作)。我还在 Azure App Service 中添加了它(在 Configuration -> Application settings 下),因为我认为我也需要它。我想我只是不确定如何阅读这些环境变量。我有点以为它会自动发生。
  • @FabricioRodriguez 默认环境变量前缀是DOTNET_ASPNETCORE_。你试过DOTNET_ConnectionStrings__MyDataContext ASPNETCORE_ConnectionStrings__MyDataContext 吗?

标签: c# azure asp.net-core environment-variables asp.net-core-webapi


【解决方案1】:

尝试使用LaunchSettings.json 指定ConnectionStrings__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"
      }
    }
  }
}

【讨论】:

    【解决方案2】:

    好的,原来唯一的问题是我在调试模式下运行 Web API(从 Visual Studio 中)。一旦发布到 Azure 应用服务,它就可以工作了。回顾一下:

    在 Azure 应用服务配置中,我添加了一个名为 ConnectionStrings__MyDataContext 的环境变量以及相关值。

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

    services.AddDbContext<LogContext>(options =>
        options.UseMySql(Configuration.GetConnectionString("MyDataContext"), new MySqlServerVersion(new Version(5, 7, 29))));
    

    就是这样!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 2016-01-21
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 1970-01-01
      相关资源
      最近更新 更多