【问题标题】:using custom types in a WCF service在 WCF 服务中使用自定义类型
【发布时间】:2011-07-26 17:00:14
【问题描述】:

我是 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,以及如何解决这个问题。 非常感谢!

【问题讨论】:

    标签: wcf


    【解决方案1】:

    将以下几行添加到您的服务接口声明中(将它们添加到 ServiceContract 属性下方):

    [ServiceKnownType(typeof(Class1))]
    [ServiceKnownType(typeof(Class2))]
    

    或者,这是推荐的方法,定义由服务导出的 DTO 对象集,并使用 [DataContract] 和 [DataMember] 属性装饰它们。

    【讨论】:

    • 感谢 Oliver Weichhold 先生,但我尝试了您的建议,但仍然遇到同样的异常。我正在尝试定义一个 DTO 对象,但有没有办法直接解决它?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    相关资源
    最近更新 更多