【问题标题】:EF Core connection string settings with azure functions and web api具有 azure 函数和 Web api 的 EF Core 连接字符串设置
【发布时间】:2020-01-07 04:41:20
【问题描述】:

我有 2 个项目 1.ASP.NET Core WEB API 2.Azure函数

两者都托管在 azure 上。 我也有不同的开发和生产帐户,因此我需要根据应用程序部署的环境有不同的连接字符串。

对于实体框架,我使用 2 个应用程序引用的单独项目。

当从 weba api 使用单独的项目时,我可以通过这种方式读取连接字符串

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
        IConfigurationRoot configuration = new ConfigurationBuilder()
                                            .SetBasePath(Path.Combine(Directory.GetCurrentDirectory()))

            .AddJsonFile("appsettings.json", optional: false)
            .AddJsonFile($"appsettings.{envName}.json", optional: false)
            .Build();

        var cs = configuration.GetConnectionString("DefaultConnection");
        optionsBuilder.UseSqlServer(cs);
    }
}

但是没有用于触发器的 appsettings.json 文件。在这种情况下我该怎么办?

【问题讨论】:

  • But there's no appsettings.json file for trigger ?你想在哪里有 appsetting.json ?
  • @TonyNgo 在部署触发器的服务器上
  • 你为什么不创建 1 ?我个人在使用 azure 函数项目时创建 appsetting.json
  • @TonyNgo 我确实创建了,但它只能在本地工作。当我通过 Visual Studio 部署 azure 函数时,appsettings.json 被省略了

标签: c# azure asp.net-core entity-framework-core azure-functions


【解决方案1】:

对于本地开发,使用Environment Variable 来存储您的连接字符串。 (在Visual Studio 中右键单击您的Azure Function Project 选择propertiesDebug,您将能够在那里添加Environment Variable。这将存储在launchsettings.json 中) 例如你可以称它为MSSQL_CONN_STR

部署到Azure 时使用Application Settings (转到Function app,单击Configuration,您可以使用与上述相同的键(MSSQL_CONN_STR)添加一个新的应用程序设置/环境变量,但使用您的production值作为连接字符串)

在您的 C# 代码中,您可以获得与上面相同的 Environment Variable

Environment.GetEnvironmentVariable("MSSQL_CONN_STR");

来自 MS 关于 Azure Function App 的应用程序设置

应用程序设置作为环境变量公开,供您的应用程序在运行时访问

【讨论】:

    猜你喜欢
    • 2020-04-14
    • 2019-06-26
    • 2018-05-28
    • 2020-03-22
    • 2015-09-14
    • 2017-05-06
    • 2017-09-22
    • 1970-01-01
    相关资源
    最近更新 更多