System.Runtime.Serialization.SerializationException 从 Azure 服务总线接收消息时

System.Runtime.Serialization.SerializationException while receiving message from Azure Service Bus

我有两个独立的应用程序,一个是 .Net Core,另一个是 .Net Framework。我在 .Net 核心控制台应用程序中创建了一个服务总线发送器。它正在使用最新的 Microsoft.Azure.WebjobsMicrosoft.Azure.Webjobs.ServiceBus nuget 包向服务总线发送消息。这是发件人的示例代码。

var message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request)));
var client = new TopicClient(connectionString, TopicName);
await client.SendAsync(message);

另一个用 .NET Framework 4.7 编写的应用程序正在侦听相同的服务总线。它使用 .Net Framework 的 nuget 包 Microsoft.Azure.WebjobsMicrosoft.Azure.Webjobs.ServiceBus 两个版本 2.3.0。下面的示例代码。

public class ListenJob
{
    public static void Listen([ServiceBusTrigger("%TopicName%", "%SubscriptionName%")] BrokeredMessage message)
    {
        var messageBody = message.GetBody<string>();
    }
}

关于从 .Net 核心控制台应用程序发送消息。其他应用程序能够检测到该消息,但我在 listener.

var messageBody = message.GetBody<string>(); 上收到以下错误

Exception while executing function: Applications Microsoft.Azure.WebJobs.Host.FunctionInvocationException : Exception while executing function: Applications ---> System.Runtime.Serialization.SerializationException : There was an error deserializing the object of type System.String. The input source is not correctly formatted. ---> System.Xml.XmlException : The input source is not correctly formatted.

在您的发送代码中,消息正文作为流发送(字节按原样发送,未编码)。你用来接收旧版 Azure 服务总线库的代码期望从这些字节中反序列化一个字符串。在编码方面,您应该使用相同的发送和接收方法。 IE。您应该使用 message.GetBody<Stream> 获得 Stream 并从流中读取字节并在需要时反序列化。更多信息 here.

为了能够按原样使用 message.GetBody<string> 将 is 作为字符串检索,您需要更改发件人的代码以发送 DataContract 二进制序列化字符串。参见 如何操作。