我使用Azure主题和订阅作为消息总线。但当我做 message.GetBody()时,我收到了一个SerializationException。我想要实现的是让一个订阅者读取BaseEvent类型的所有事件,并且每个事件都有自己的订阅者。但是,当我尝试序列化主体(BaseEvent)时,它失败了。那么如何序列化主体以获取UserEvent和TeamEvent?我的代码如下所示:
public abstract class BaseEvent
{
public long ActivityId { get; set; }
}
public class UserEvent
{
public string Name { get; set; }
}
public class TeamEvent
{
public string Name { get; set; }
}
我将它们添加到消息总线中,如下所示:
public async Task HandleAsync(BaseEvent request)
{
var message = new BrokeredMessage(request)
{
CorrelationId = request.Id.ToString()
};
await topicClient.SendAsync(message);
await topicClient.CloseAsync();
}
当我要从公交车上阅读时,我确实喜欢这样:
BrokeredMessage message;
while ((message = client.Receive(new TimeSpan(0, 0, 5))) != null)
{
models.Add(message.GetBody<BaseEvent>()); // THIS FAILS SerlizationException
message.Complete();
}
答案 0 :(得分:0)
作为BrokeredMessage Constructor声明:
public BrokeredMessage(
Object serializableObject
)
它通过使用带有二进制XmlDictionaryWriter的DataContractSerializer从给定对象初始化BrokeredMessage类的新实例。因此BaseEvent类必须支持DataContractSerializer。如何操作,请参阅Serialization and Deserialization