我是WCF的新手,现在陷入了在WCF服务中使用自定义类型的问题。
我在TestClass项目中有两个类Class1和Class2
public Class1: ArrayList{
public string street;
}
public Class2{
public string name;
public string address;
}
我的WCF服务TestService包含使用上面两个类的函数DoSomething
public string DoSomething(Class1 c1){
return c1.street;
}
当试图调用此函数时
Class1 c1 = new Class1();
Class2 c2 = new Class2();
c1.Add(c2);
ServiceClient1.Dosomething(c1);
我得到了例外
There was an error while trying to serialize parameter http://tempuri.org/:c1. The
InnerException message was 'Type 'WebApplication1.Class2' with data contract name
'Class2:http://schemas.datacontract.org/2004/07/WebApplication1' is not expected. Add
any types not known statically to the list of known types - for example, by using the
KnownTypeAttribute attribute or by adding them to the list of known types passed to
DataContractSerializer.'. Please see InnerException for more details.
任何人都可以告诉我如何为在WCF服务之外定义的类添加DataContract,以及如何解决此问题。 非常感谢!
答案 0 :(得分:1)
将以下行添加到服务接口声明中(将它们添加到ServiceContract属性下面):
[ServiceKnownType(typeof(Class1))]
[ServiceKnownType(typeof(Class2))]
或者,这是推荐的方法,定义服务导出的DTO对象集,并使用[DataContract]和[DataMember]属性修饰它们。