我正在将.NET Core 2用于需要在服务总线上放置消息并由旧版.NET 4.6接收器读取的应用程序。接收方也会收听来自其他遗留应用程序的消息。
旧版发件人:
UserData obj = new UserData()
{
id = 1,
name = "Alisha"
};
BrokeredMessage message = new BrokeredMessage(consentInstated);
_client.Send(message);
传统接收者:
var dataObj = objBrokeredMessage.GetBody<UserData>();
businessFunc(dataObj.id, dataObj.name);
.NET Core 2发件人,如https://stackoverflow.com/a/45069423/1773900
中所述var ser = new System.Runtime.Serialization.DataContractSerializer(typeof(UserData));
var ms = new MemoryStream();
ser.WriteObject(ms, objUserData);
var message = new Message(ms.ToArray());
_client.Send(message);
但是,接收方无法反序列化消息并引发以下错误
System.Runtime.Serialization.SerializationException:有一个 错误反序列化UserData类型的对象。输入源是 格式不正确。 ---&GT; System.Xml.XmlException:输入 来源格式不正确。
如何让两个发件人都使用相同的接收器?
答案 0 :(得分:5)
BrokeredMessage
正在使用XML二进制读取器反序列化消息。所以你的发送部分应该是这样的:
var ser = new DataContractSerializer(typeof(UserData));
var ms = new MemoryStream();
XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(ms);
ser.WriteObject(binaryDictionaryWriter, obj);
binaryDictionaryWriter.Flush();
var message = new Message(ms.ToArray());
答案 1 :(得分:3)
我们可以直接从.net核心端发送序列化json对象字符串,我们可以在.net端获取带有以下代码的消息。它在我身边正常工作。
var dataObj = message.GetBody<UserData>(new DataContractJsonSerializer(typeof(UserData)));
.net核心方发送消息代码:
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(objUserData));
_client.SendAsync(new Message{Body = body,ContentType = "text/plain"}).Wait();
.net端接收消息代码:
var dataObj = message.GetBody<UserData>(new DataContractJsonSerializer(typeof(UserData)));
答案 2 :(得分:0)
我也遇到了同样的问题,但是没有一种解决方案有效。对我来说,下面的代码有效
// model is the object that you want to sent to Topic
Model model = new Model();
var serializator = new DataContractSerializer(typeof(string));
var json = JsonConvert.SerializeObject(model);
var memoryStream = new MemoryStream();
XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(memoryStream);
serializator.WriteObject(binaryDictionaryWriter, json);
binaryDictionaryWriter.Flush();
// below message can be sent to Topic via .NET Core and will be properly deserialized in .NET Framework subscriber
var message = new Message(memoryStream.ToArray());
var client = new TopicClient(_endpoint, _channelName );
await client.SendAsync(message);