gpt4 book ai didi

Azure 服务总线队列 - 使用 BrokeredMessage 进行序列化

转载 作者:行者123 更新时间:2023-12-02 08:08:41 24 4
gpt4 key购买 nike

尝试提交消息正文中包含对象的队列消息,但在 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; }
}

请帮忙定位问题。

最佳答案

您的数据协定中缺少 [KnownType] 属性,这就是您的消息无法序列化的原因。详细解释可参见hehe .

只需添加 [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>();
}
}

关于Azure 服务总线队列 - 使用 BrokeredMessage 进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26792345/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com