1

尝试使用消息正文中的对象提交队列消息,但在以下行中收到 BrokeredMessage 异常

QueueClient queueClient = QueueClient.CreateFromConnectionString(_connectionString, _queuePathName);
var data = new ABSurvey
                {
                    name = "somename",
                    version = 1,
                    language = "eng",
                    SelfSurvey = new Survey()
                    {
                        SurveyItems = new List<ISurveyItem>() { new SurveyItem(){IsSelected = true, ItemId = 1}},
                        SurveyPerception = Constants.Perception.Self
                    },
                    SelfConcept = new Survey()
                    {
                        SurveyItems = new List<ISurveyItem>() { new SurveyItem(){IsSelected = true, ItemId = 1}},
                        SurveyPerception = Constants.Perception.SelfConcept
                    }
                };
                BrokeredMessage message = new BrokeredMessage(data);
                queueClient.Send(message); 

异常消息 -类型为“.Survey”,数据合同名称为“Survey: http://schemas.datacontract.org/2004/07/namespace ”。考虑使用 DataContractResolver 或将任何静态未知的类型添加到已知类型列表中 - 例如,通过使用 KnownTypeAttribute 属性或将它们添加到传递给 DataContractSerializer 的已知类型列表中。

这些是我拥有的模型 -

    [DataContract]
public class ABSurvey
{
    [DataMember] public string name;
    [DataMember] public int version;
    [DataMember] public string language;
    [DataMember] public ISurvey SelfSurvey;
    [DataMember] public ISurvey SelfConcept;
}

[DataContract]
public class SurveyItem : ISurveyItem
{
    [DataMember]
    public int ItemId { get; set; }
    [DataMember]
    public bool IsSelected { get; set; }
    public SurveyItem()
    {
        ItemId = -1;
        IsSelected = false;
    }
}

[DataContract]
public class Survey : ISurvey
{
     [DataMember]
    public IList<ISurveyItem> SurveyItems { get; set; }
     [DataMember]
    public Constants.Perception SurveyPerception { get; set; }
    public Survey()
    {
        SurveyItems = new List<ISurveyItem>();
    }
}

public interface ISurvey
{
    [DataMember]
    IList<ISurveyItem> SurveyItems { get; set; }
    [DataMember]
    Constants.Perception SurveyPerception { get; set; }
}
public interface ISurveyItem
{
    [DataMember]
    int ItemId { get; set; }
    [DataMember]
    bool IsSelected { get; set; }
}

请帮助定位问题。

4

1 回答 1

3

您的数据合同缺少[KnownType]属性,这就是您的消息无法序列化的原因。详细解释可以找到嘿嘿

只需添加 [KnownType] 属性来告诉序列化器可以使用哪个具体实现:

[KnownType(typeof(Survey))]
[DataContract]  
public class ABSurvey
{
    [DataMember]
    public string name;
    [DataMember]
    public int version;
    [DataMember]
    public string language;
    [DataMember]
    public ISurvey SelfSurvey;
    [DataMember]
    public ISurvey SelfConcept;
}

[KnownType(typeof(SurveyItem))]
[DataContract]
public class Survey : ISurvey
{
    [DataMember]
    public IList<ISurveyItem> SurveyItems { get; set; }

    public Survey()
    {
        SurveyItems = new List<ISurveyItem>();
    }
}
于 2014-11-07T11:01:24.503 回答