服务总线消息反序列化 System.String 类型的对象时出错,但消息格式正确 json

Service bus message Error deserializing the object of type System.String but message format is correct json

服务总线消息反序列化 System.String 类型的对象时出错,但消息格式正确 json。

使用代码向主题发送消息 -

 topicClient = new TopicClient(ServiceBusConnectionString, TopicName);

                // Create a new message to send to the topic.
                string messageBody = string.Format("{{ \"Id\":\"{0}\",\"Name\":\"{1}\" }}", "121", "Demo");
                var message = new Message(Encoding.UTF8.GetBytes(messageBody));

                // Send the message to the topic.
                await topicClient.SendAsync(message);

进入服务总线主题的消息看起来像 -

{ "Id":"121","Name":"Demo" }

从主题读取消息时出现以下错误 -

string currentMessageData = currentMessage.GetBody<string>();

There was an error deserializing the object of type System.String. The input source is not correctly formatted.

我认为问题在于您的消息被写成 stream 而不是 string

而不是

string currentMessageData = currentMessage.GetBody<string>();

尝试

Stream stream = message.GetBody<Stream>();
StreamReader reader = new StreamReader(stream);
string currentMessageData = reader.ReadToEnd();