c# - Azure Function v2 和连接字符串

标签 c# azure azure-functions

我有以下 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”添加到“连接字符串”时:

enter image description here

我的代码不起作用:

            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");

关于c# - Azure Function v2 和连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60791103/

相关文章:

azure - 无法引用 Azure Functions 中的 Polly 或其他包

azure - 在 Azure Function App 中查找高 CPU 的特定函数

C# JSON 从 List<> 获取数据

javascript - C# Web浏览器以编程方式关闭JS确认框

c# - 我们可以在 WPF 中的 DataGrid 单元格内有一个网格吗?

azure - 如何在 Azure VM 中阻止除单个 IP 之外的所有人的互联网

sql-server - SQL 数据库从 Azure VM 转换到 Azure SQL 数据库 - 新数据库的大小明显更小?

c# - 不支持写入压缩流。使用 System.IO.GZipStream

c# - 发生错误时,如何让 Azure Insights 记录入口方法(如果不是所有方法)的请求有效负载?

.net - 从 Azure Web API 使用 Azure Analysis Services 数据