首页 > 解决方案 > 使用 azure appsettings 在 azure webjob 中读取 EventHubTrigger 的连接字符串

问题描述

我正在使用 .Net core 3.1 编写一个 azure webjob 并从 eventthub 读取事件。我已经能够在本地工作,我从本地 appsettings.json 和 appsettings.dev.json 读取所有设置。 public async Task ProcessEvent([EventHubTrigger("%EventHubName%", Connection = "EventHubConfigConnectionString", ConsumerGroup = "%ConsumerGroupName%")] EventData eventData)

但是,我现在尝试使用 azure appservice appsettings 来存储连接字符串,其中应用设置作为环境变量公开,我将其添加到配置中: Configuration = new ConfigurationBuilder() .AddEnvironmentVariables().Build();

但我仍然得到错误: System.ArgumentNullException: Value cannot be null. (Parameter 'connectionString') at Microsoft.Azure.EventHubs.Primitives.Guard.ArgumentNotNullOrWhiteSpace(String argumentName, String value)

我验证变量名称是相同的。我在线阅读,看起来 EventHubTrigger 的连接字符串必须存在于 appsettings 文件中而不是环境变量中?

我错过了什么吗?

标签: c#azureasp.net-coreazure-webjobsazure-eventhub

解决方案


您的appSettings.json文件中应该有一个条目,我会在下面的connectionStrings部分下说:

{
  "AppInsights_InstrumentationKey": "",
  "ConnectionStrings": {
    "EventHubConfigConnectionString": ""
  }
}

我认为在 Azure 门户中,对于您的应用服务,您可以设置一个新的连接字符串,其名称EventHubConfigConnectionString将覆盖 appSettings.json 文件中的名称:

应用服务配置刀片下的连接字符串部分

然后在你Program.cs有以下可能:

Configuration = new ConfigurationBuilder()
                    .SetBasePath(Environment.CurrentDirectory)
                    .AddJsonFile("appSettings.json", optional: true)
                    .AddEnvironmentVariables()
                    .Build();

希望这可以帮助。


推荐阅读