我有一个 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; }
}
最佳答案
有两种选择:
具体集合类型(List等)作为返回值,为WCF提供序列化机制(Collection Types in Data Contracts, MSDN)。
使用已知数据类型 ( Data Contract Known Types, MSDN )。
关于c# - WCF DataContract - 无法返回复杂类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9102065/