WCF 上的 DataContract 和层次结构问题
我的 wcf 项目中的对象有问题。 我可以说这个对象:
[DataContract(Name="ClassA")]
public class Person{
//---attributes---
}
[DataContract(Name="ClassB")]
public class Men : Person{
//---attributes---
}
其中 ClassB 是另一侧 ClassA 的子级。 然后我有一个 post 方法:
[OperationContract]
[WebInvoke(UriTemplate= "Person", ResponseFormat = WebMessageFormat.Json, Method= "POST")]
public string PostPerson(Person person) {
if(person is Men){
//code...
}
}
问题是我收到了这个人(在另一边,他们将我作为 ClassB 发送),但这个人是 Men 返回 false.. 为什么?
i have a problem with an object in my wcf project.
I have lets say this object:
[DataContract(Name="ClassA")]
public class Person{
//---attributes---
}
[DataContract(Name="ClassB")]
public class Men : Person{
//---attributes---
}
Where ClassB is child of ClassA on the other side.
Then i have a method that is post:
[OperationContract]
[WebInvoke(UriTemplate= "Person", ResponseFormat = WebMessageFormat.Json, Method= "POST")]
public string PostPerson(Person person) {
if(person is Men){
//code...
}
}
The thing is that i receive the person (in the other side, they sendme as a ClassB) but the person is Men returns false.. why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将
[ServiceKnownType(typeof(Men))]
属性添加到 PostPerson 方法。You need to add the
[ServiceKnownType(typeof(Men))]
attribute to the PostPerson method.正如瑞安·格罗斯(Ryan Gross)提到的,你需要男人成为一种众所周知的类型。 这里有一个类似的问题/答案。链接文章中未提及的一个选项是已知类型属性。这是我过去使用过的代码示例。前提条件是此类是所有数据协定的基类,并且所有数据协定都位于同一个程序集中:
As Ryan Gross mentions, you need Men to be a known type. Here's a similar question/answer here on SO. One option not mentioned in the linked article is the KnownType attribute. Here's an example of code I've used in the past. The prerequisite is that this class is the base class for all of your data contracts and all of your data contracts are in the same assembly: