我有以下 local.settings.json
文件:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"AzureWebJobsDashboard": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"SureMdmApiKey": "xxx",
"SureMdmApiUrl": "xxx",
"SureMdmUsername": "xxx",
"SureMdmPassword": "xxx"
},
"ConnectionStrings": {
"StorageConnectionString": "aaaa",
"DataContext": "aaaa"
}
}
然后我在 Startup.cs 文件中有以下代码:
[assembly: FunctionsStartup(typeof(FunctionAppSureMdmSync.Startup))]
namespace FunctionAppSureMdmSync
{
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var services = builder.Services;
services.AddTransient<ISureMdmService>(s => new SureMdmService(
url: System.Environment.GetEnvironmentVariable("SureMdmApiUrl"),
username: System.Environment.GetEnvironmentVariable("SureMdmUserName"),
password: System.Environment.GetEnvironmentVariable("SureMdmPassword"),
apiKey: System.Environment.GetEnvironmentVariable("SureMdmApiKey")
));
var connString = System.Environment.GetEnvironmentVariable("ConnectionStrings:DataContext");
services.AddDbContext<DataContext>(options => options
.UseSqlServer(connString, x => x.UseNetTopologySuite()));
services.AddTransient<ITabletGroupService, TabletGroupService>();
services.AddTransient<ITabletService, TabletService>();
}
}
}
并且在本地运行良好
但是当我将此函数发布到 Azure 门户并转到“配置”并将“DataContext”添加到“连接字符串”时:
我的代码不起作用:
var connString = System.Environment.GetEnvironmentVariable("ConnectionStrings:DataContext");
如何获取连接字符串?我希望它在本地和 Portal Azure 上都能工作?
最佳答案
我发现要在 Startup
中访问 IConfiguration
,您需要构建一个临时服务提供者,然后将其丢弃。最近可能有更好的方法,但它仍然工作正常:
var configuration = builder.Services.BuildServiceProvider().GetService<IConfiguration>();
然后,不要使用 System.Environment.GetEnvironmentVariable()
,而是使用 IConfiguration
(这同样适用于您的所有配置):
var connString = configuration.GetConnectionString("DataContext");
https://stackoverflow.com/questions/60791103/
相关文章:
python - 有没有办法从图形图像中提取数据并将其存储在 Excel 工作表或 csv 文件中?
date - 如何在 DART(Flutter)中舍入最接近 30 分钟间隔的日期时间?
azure-devops - 创建与 Azure 资源管理器的服务连接时出错 : azure pip
azure-devops - 如何将 Yarn 注册表用作 Azure DevOps 工件上游源?
typescript - 在另一个接口(interface)中使用 Typescript 接口(in
node.js - 从 lambda 向 sns 主题发布消息