如何在WCF消息中发送自定义对象

本文关键字:自定义 对象 消息 WCF | 更新日期: 2023-09-27 18:12:26

我想在system.servicemodel.Channels.Message中发送一个自定义对象。像

public class person
{
    string Id;
    string Name;
}
MessageVersion mv = MessageVersion.Create(Soap12);
String action = "Msg";
Message msg = Message.Create(mv, action, new person());
serviceref.ProcessMsg(msg) // this is my service reference in client
//when i tried to access this in Service like 
person p = msg.GetBody<person>()
//I am getting an serialization exception
//I have the Person class on both client and service side
有谁能帮我找出我的错误吗?

如何在WCF消息中发送自定义对象

看起来你正在寻找一个数据合约:

using System.Runtime.Serialization;
[DataContract]
public class person
{
    [DataMember]
    string Id;
    [DataMember]
    string Name; 
}

查看使用数据合约了解更多关于数据合约和WCF的信息。

编辑

不确定这是否会奏效,但正如我在回应你的评论时指出的那样,有一个重载的CreateMessage方法,它需要一个XmlObjectSerializer。关于它的MSDN文档相当薄,但我认为这样的东西可以做到:

Message msg = Message.Create(mv, action, new person(), new DataContractSerializer(typeof(person)));

我还没有测试过这个,但至少它可以让你指向正确的方向。

DataContractSerializer将需要提供一个数据合约(person在我的回答的第一部分)。