c# - Azure 服务总线消息在运行时在订阅中反序列化为未知类型

标签 c# .net serialization azureservicebus azure-servicebus-subscriptions

令人惊讶的是,但我还没有找到一个示例,其中订阅收到的消息可能具有不同的类型,并且需要知道该类型才能使用正确的类型反序列化其内容。 This is related但它没有考虑这种情况

我有一个发布订阅者场景。对于订阅者,创建 Message可以按照 https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-dotnet-how-to-use-topics-subscriptions 使用 Azure 服务总线库进行发布 我需要传递一个字节数组。它似乎没有类似自定义元数据之类的东西,我可以用它来指定消息的程序集类型或类似的内容。

当订阅收到消息时,它必须反序列化它,但我无法知 Prop 体消息是什么类型,以便执行JsonConvert.DeserializeObject<TDestType>(Encoding.UTF8.GetString(message.Body))

有人有任何链接或示例来实现此目的吗?或者建议的做法是仅使用主题和主题订阅来处理一种类型的消息? (我对此表示怀疑,但我知道例如 MassTransit 会在幕后为每条消息创建一个主题。)


更新 1:现在我将使用 Message 中的 ContentType 属性来存储 EventType,以便订阅者可以使用它来反序列化。但如果感觉“hacky”,因为该字段应该存储格式类型(json、xml 等)

最佳答案

It does not seem to have anything like custom metadata that I could use to specify the assembly type for the message or similar.

Azure 服务总线确实为每条消息提供了可用作 UserProperties 的 header /元数据。一个主题可以接收多种消息类型,订阅者可以使用订阅查看他们将处理哪些消息。订阅可以是简单的订阅,也可以使用 correlation filters 来利用消息的 ContentType 属性。或者有更高级的SQL filters提供更先进的订阅机制。

For now I'll use the ContentType property at the Message to store the EventType so that the suscriptor can use it to deserialize. But if feels "hacky" because this field is supposed to store the format type (json, xml, etc.)

您可以保留 ContentType 进行序列化,并使用自定义 header 来过滤订阅者的消息。或者您可以选择将两者都存储在自定义 header 中。这是你的决定。

It's surprising, but I haven't yet found a sample where the Message received at a subscription could be of different types and the type needs to be known in order to deserialize its content with the right type.

这就是 NServiceBus使用 Azure 服务总线作为传输。单个接收者(端点)可以处理不同的消息类型。订阅者创建过滤器来检查自定义 header 值以识别消息的类型。

关于c# - Azure 服务总线消息在运行时在订阅中反序列化为未知类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60613372/

相关文章:

c# - AutoResetEvent.WaitOne() 导致死锁

c++ - 在 perl 和 cpp 之间共享数据结构

c# - 我想从 GridView 中删除记录。在此之前要求确认,如 "Are you sure to delete?"

c# - 什么时候使用 PreRender 而不是 PageLoad?

c# - 在 ALB 上使用 Cognito 用户池进行 ASP.NET Core 身份验证

unity-game-engine - String.Format 显示 SerializeField 数据中的旧实例数据 - 如何修复?

algorithm - 哪些应用程序/游戏状态 "delta compression"技术/算法确实存在?

c# - 使用 key 在 azure 搜索索引中查找文档

mysql - 未解析成员 'MySql.Data.MySqlClient.MySqlException,MySql.Data, Version=6.9.9.0,

c# - 如何处理 TransactionInDoubtException