我尝试使用Microsoft的Serivce Bus Brokered Message 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;
}