我正在尝试使用 Microsoft 的服务总线代理消息 API,但在尝试使用派生类型时遇到了反序列化问题。似乎代码无法识别已知类型,并且在序列化这些类型并在其他服务之间返回它们时我没有问题。有什么我想念的吗?我已经浏览了大量的 SO 帖子,但似乎没有任何效果。
这是消息结构:
[DataContract]
[KnownType(typeof(ActivityBus))]
public class BaseBusType
{
[DataMember]
public int Id { get; set; }
}
[DataContract]
public class ActivityBus : BaseBusType { }
到目前为止,我已经尝试过这些选项:
// In the sending function
var brokeredMessage = new BrokeredMessage(reader.ReadToEnd());
topicClient.Send(obj);
// In the receiving function
List<Type> knownTypes = new List<Type>() { typeof(ActivityBus) };
var serializer = new DataContractSerializer(typeof(BaseBusType), knownTypes); // listed knowntypes for brevity
var messageBody = message.GetBody<BaseBusType>(serializer);
还:
// In the sending function
using (MemoryStream memoryStream = new MemoryStream())
using (StreamReader reader = new StreamReader(memoryStream))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(memoryStream, data);
memoryStream.Position = 0;
var brokeredMessage = new BrokeredMessage(reader.ReadToEnd());
topicClient.Send(brokeredMessage);
}
// In the receiving function
using (Stream stream = new MemoryStream())
{
var str = brokeredMessage.GetBody<string>();
byte[] data = System.Text.Encoding.UTF8.GetBytes(str);
stream.Write(data, 0, data.Length);
stream.Position = 0;
List<Type> knownTypes = new List<Type>() { typeof(Activitybus) };
var deserializer = new DataContractSerializer(typeof(BaseBusType), knownTypes);
var reader = XmlReader.Create(new StringReader(str));
var obj = deserializer.ReadObject(reader);
return (T)obj;
}