我有2个项目 1.ASP.NET Core WEB API 2.Azure功能
两者都托管在 azure 上。 我也有不同的开发和生产帐户,因此我需要根据应用程序部署的环境有不同的连接字符串。
对于 Entity Framework ,我使用两个应用程序引用的单独项目。
当从 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 文件。这种情况我能做什么?
最佳答案
对于本地开发,请使用环境变量
来存储连接字符串。
(在 Visual Studio
中右键单击您的 Azure Function Project
,选择 properties
、Debug
,您将能够添加那里的环境变量
。这将存储在launchsettings.json
中)
例如,您可以将其命名为 MSSQL_CONN_STR
部署到 Azure
时使用应用程序设置
(转到功能应用程序
,单击配置
,您可以使用与上面相同的键(MSSQL_CONN_STR
)添加一个新的应用程序设置/环境变量,但使用您的连接字符串的生产
值)
在您的 C# 代码中,您可以获得与上面相同的环境变量
Environment.GetEnvironmentVariable("MSSQL_CONN_STR");
来自 MS 关于 Azure Function App 的应用程序设置
Application Settings are exposed as environment variables for access by your application at runtime
关于c# - 带有 azure 函数和 Web api 的 EF Core 连接字符串设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57785818/