使用EventData[]绑定的C#独立进程Azure Function触发异常
问题:EventHub触发的独立进程Azure Functions使用EventData绑定时序列化失败
开发一个由EventHub触发的C#独立工作进程Azure Function,目标是将带标头的EventData列表输出到另一个EventHub。使用string[]绑定时函数运行正常,但使用Azure.Messaging.EventHubs中的EventData绑定时,控制台抛出以下错误:
System.Private.CoreLib: Exception while executing function: Functions.MyFunction. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'eventDatas'. Azure.Core.Amqp: Serialization failed due to an unsupported type, System.Byte[]. Executed 'Functions.MyFunction' (Failed, Id=4a2fcfa1-0042-4cb8-92d6-75289685b4dd, Duration=15ms) System.Private.CoreLib: Exception while executing function: Functions.MyFunction. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'eventDatas'. Azure.Core.Amqp: Serialization failed due to an unsupported type, System.Byte[].
项目文件配置
<TargetFramework>net7.0</TargetFramework> <AzureFunctionsVersion>v4</AzureFunctionsVersion> ... <PackageReference Include="Azure.Messaging.EventHubs" Version="5.9.2" /> <PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.19.0" /> <PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.EventHubs" Version="5.5.0" /> <PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.14.0" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
函数代码
using Azure.Messaging.EventHubs; using Microsoft.Azure.Functions.Worker; using Microsoft.Extensions.Logging; using my.Models; using Newtonsoft.Json; namespace my.function { public class MyFunction { [EventHubOutput("EventHubOutput", Connection = "EventHubOutputConnectionString")] [FixedDelayRetry(5, "00:00:10")] [Function("MyFunction")] public EventData[] Run([EventHubTrigger("EventHubInput", Connection = "EventHubInputConnectionString", IsBatched = true)] EventData[] eventDatas) { List<EventData> eventDataOutputs = new List<EventData> { }; // 接收事件 foreach (EventData eventData in eventDatas) { // 序列化事件内容 string eventJsonBody = eventData.EventBody.ToString(); MyObject? myObject = JsonConvert.DeserializeObject<MyObject>(eventJsonBody); // 拆分嵌套元素并添加到输出列表 if (myObject != null) { eventDataOutputs.AddRange(myObject.NestedFields.Select(nestedElement => new EventData(JsonConvert.SerializeObject(nestedElement)))); } } return eventDataOutputs.ToArray(); } } }
MyObject模型类
namespace my.Models { using Newtonsoft.Json; public class MyObject { [JsonProperty("randomField")] public string RandomField { get; set; } [JsonProperty("nestedFields")] public NestedField[] NestedFields { get; set; } } }
NestedField模型类
namespace my.Models { using Newtonsoft.Json; public class NestedField { [JsonProperty("randomFieldNested")] public string RandomField { get; set; } [JsonProperty("time")] public DateTimeOffset Time { get; set; } [JsonProperty("longField")] public long LongField { get; set; } } }
解决方法(更新)
升级EventHubs相关包到新版本后,问题解决,函数能够正常接收并处理事件。
内容的提问来源于stack exchange,提问作者Ceci Semble Absurde.
相关产品推荐
相关产品推荐

