c# - WCF DataContract - 无法返回复杂类型

标签 c# wcf web-services ienumerable

我有一个 WCF 服务,它有返回 IEnumerable<T> 的方法对象的集合,也是一个复杂的类型,OrganizationCollection ,它有几个属性,每个属性都是 IEnumerable<T>不同类型的。我相信我已经正确设置了我的服务契约(Contract),并定义了我的类型 DataContract/DataMember正确。返回 OrganizationCollection 的方法失败并出现异常。我知道该方法起作用,因为我有单元测试和集成测试来测试它。只有在使用实时和已部署的服务运行时才会失败。我什至将类型指定为 ServiceKnownType ,但无济于事。我需要做什么来配置服务才能返回复杂类型,如 OrganizationCollection

注意:WCF 服务正在运行 basicHttpBinding ,并被安置在一个ServiceHost在 Windows 服务中。

[System.ServiceModel.CommunicationException] {"An error occurred while receiving the HTTP response to http://localhost:8799/MyService. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details."} System.ServiceModel.CommunicationException

[ServiceBehavior(IncludeExceptionDetailInFaults = true, AutomaticSessionShutdown = false, InstanceContextMode = InstanceContextMode.Single)]
[ServiceKnownType(typeof(OrganizationCollection))]
public class MyService: IClientService
{ 
    // ...
}

[ServiceContract]
public interface IClientService
{
    // This works:
    [OperationContract]
    IEnumerable<BookSvc> GetBooks(DateTime sinceDate);

    // This fails, with the above exception:
    [OperationContract]
    OrganizationCollection GetOrganizations(DateTime sinceDate);
}

BookSvc[DataContract] 定义每个属性都有 [DataMember] .教师和学生类(class)也是如此。属性都是原始类型。 OrganizationCollection定义为:

[DataContract]
public class OrganizationCollection
{
    [DataMember]
    public IEnumerable<Teacher> Teachers { get; set; }

    [DataMember]
    public IEnumerable<Student> Students { get; set; }
}

最佳答案

有两种选择:

  1. 具体集合类型(List等)作为返回值,为WCF提供序列化机制(Collection Types in Data Contracts, MSDN)。

  2. 使用已知数据类型 ( Data Contract Known Types, MSDN )。

关于c# - WCF DataContract - 无法返回复杂类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9102065/

相关文章:

c# - WCF wsHttpBinding 客户端证书身份验证,无需在客户端中使用存储

java - Android 客户端连接到 RestFul Webservice

c# - 从 ASP.NET Core Web 方法提供 SOAP

c# - MicrosoftAppId : '' is unauthorized to post to connector 的安全 token

c# - 从后台线程捕获异常

c# - "\"@\"在代码块的开头无效

c# - 什么时候关闭 WCF 客户端?

windows - 如何说服客户升级到 WCF 或为 Remoting 和 WCF 保留两个代码库

嵌入 HTML 的 JAVA Applet 在操作过程中挂起

c# - 我们如何在 C# 中访问 C 指针指向的值?