Microsoft.Azure.ServiceBus 2.0.0 消息的意外编码或内容

Unexpected encoding or content of Microsoft.Azure.ServiceBus 2.0.0 message

我正在使用 Microsoft.Azure.ServiceBus 2.0.0 订阅队列消息,当我使用 Encoding.UTF8.GetString(serviceBusMessage.Body).[=14= 时出现意外字符]

看起来消息内容应该是有效的XML,但肯定不是。

发送消息的代码,使用旧的 WindowsAzure.ServiceBus 4.1.6 库,如下所示:

private void SendToProcessingQueue(Guid accountId, Message msg) { string queueName = msg.MessageType.ToLower(); var client = CreateQueueClient(queueName); client.Send(new BrokeredMessage(new MessageHint() { AccountId = accountId, MessageId = msg.Id, MessageType = msg.MessageType })); }

新旧库不兼容吗?

是否不兼容 - 在将 class 库重新实现为 .NET 4.7 而不是 .NET Standard 2.0 并引用 WindowsAzure.ServiceBus 4.1.7 后,我能够解析消息 而不是 Microsoft.Azure.ServiceBus 2.0.0。 API差不多,所以我只用了15分钟就重新实现了。

更新:如果有人知道如何在两个版本之间交换消息,请post另一个描述应该如何完成的答案。

要创建兼容的消息,您似乎需要使用 DataContractBinarySerializer 对它们进行编码。值得庆幸的是,他们在 Microsoft.Azure.ServiceBus nuget 包中包含了一个。兼容性序列化函数如下所示:

byte[] Serialize<T>(T input)
{
    var serializer = Microsoft.Azure.ServiceBus.InteropExtensions.DataContractBinarySerializer<T>.Instance;
    MemoryStream memoryStream = new MemoryStream(256);
    serializer.WriteObject(memoryStream, input);
    memoryStream.Flush();
    memoryStream.Position = 0L;
    return memoryStream.ToArray();
}

因此,使用新库发送您的消息将如下所示:

private void SendToProcessingQueue(Guid accountId, Message msg)
{
    string queueName = msg.MessageType.ToLower();
    var client = CreateQueueClient(queueName);
    client.Send(new Message(Serialize(new MessageHint()
    {
        AccountId = accountId,
        MessageId = msg.Id,
        MessageType = msg.MessageType
    })));
}

如果您使用新库从旧库接收消息,新库的开发人员提供了一种扩展方法 Microsoft.Azure.ServiceBus.InteropExtensions.MessageInteropExtensions.GetBody<T> 以兼容的方式读取消息,这对您很有帮助。你这样使用它:

MessageHint hint = message.GetBody<MessageHint>();