You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级至Azure.Messaging.EventHubs后,如何将EventData转换为byte[]?

EventData 转 byte[]:Azure.Messaging.EventHubs 升级适配方案

我正在将项目中的包从Microsoft.ServiceBus.Messaging升级至Azure.Messaging.EventHubs,需要将EventData转换为byte[]。在旧包中可通过eventData.GetBytes()方法实现转换,但尝试使用以下BinaryFormatter序列化方式转换新包中的Azure.Messaging.EventHubs.EventData时:

private byte[] ObjectToByteArray(Object obj)
{
    if (obj == null)
        return null;

    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);

    return ms.ToArray();
}

出现异常:

System.Runtime.Serialization.SerializationException: 'Type 'Azure.Messaging.EventHubs.EventData' in Assembly 'Azure.Messaging.EventHubs, Version=5.8.1.0, Culture=neutral' is not marked as serializable.'


解决方案

新的Azure.Messaging.EventHubs.EventData类无需通过序列化转换,直接读取消息体属性即可获取字节数组:

  • 针对Azure.Messaging.EventHubs 5.x及正式版
    EventData.Body为BinaryData类型,直接调用ToArray()方法即可:
private byte[] EventDataToByteArray(Azure.Messaging.EventHubs.EventData eventData)
{
    return eventData?.Body?.ToArray();
}
  • 针对早期预览版本(5.x之前)
    若EventData.Body为ReadOnlyMemory<byte>类型,转换方式如下:
private byte[] EventDataToByteArray(Azure.Messaging.EventHubs.EventData eventData)
{
    if (eventData == null)
        return null;
        
    return eventData.Body.ToArray();
}

注意事项

BinaryFormatter已被微软标记为不安全的序列化方案,且新的EventData类未标记可序列化特性,因此不能用该方式转换。直接访问Body属性是官方推荐的高效、安全的获取消息内容方式。

内容的提问来源于stack exchange,提问作者prasanthi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:52:18