从 WCF 服务返回自定义 类 时出现 SerializationException

SerializationException when returning custom classes from a WCF service

我有以下 classes...

public abstract class Fallible<T> {
}

public class Success<T> : Fallible<T> {
  public Success(T value) {
    Value = value;
  }

  public T Value { get; private set; }
}

这方面的背景可以在 中找到,但您不需要阅读 post,因为上面的 classes 是看到问题。

如果我有这样一个简化的 WCF 服务调用...

[OperationContract]
public Fallible<Patient> GetPatient(int id) {
  return new Success<Patient>(new Patient {ID = 1,FirstName = "Jim",Surname = "Spriggs"});
}

...然后当我尝试从使用它的 WPF 应用程序(或 WCF 测试客户端)调用服务时,我收到 CommunicationException 异常...

There was an error while trying to serialize parameter :GetPatientResult. The InnerException message was 'Type 'PhysioDiary.Entities.FallibleClasses.Success`1[[PhysioDiary.Entities.Patient, PhysioDiary.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name > 'SuccessOfPatient0yGilFAm:http://schemas.datacontract.org/2004/07/PhysioDiary.Entities.FallibleClasses' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or 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 the serializer.'. Please see InnerException for more details.

...内部 SerializationException 异常...

Type 'PhysioDiary.Entities.FallibleClasses.Success`1[[PhysioDiary.Entities.Patient, PhysioDiary.Entities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' with data contract name > 'SuccessOfPatient0yGilFAm:http://schemas.datacontract.org/2004/07/PhysioDiary.Entities.FallibleClasses' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or 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 the serializer.

我已经尝试将 [DataContract] 添加到 class 并将 [DataMember] 添加到每个 属性,并为所有四个添加 [KnownType] 属性class 涉及,并在服务合同中为每个人添加 [ServiceKnownType],但没有任何帮助。

我已经阅读了同一个问题的无数答案,但没有找到任何有效的答案。我的服务 return 其他自定义 classes,它们都可以毫无问题地序列化。

谁能解释一下这里的问题是什么?如果我没有提供足够的信息,请告诉我。

事实证明,我需要做的就是用 [ServiceKnownType] 基本类型和每个派生类型的属性装饰服务方法...

[OperationContract]
[ServiceKnownType(typeof(Fallible<Patient>)]
[ServiceKnownType(typeof(Success<Patient>)]
[ServiceKnownType(typeof(BadIdea<Patient>)]
[ServiceKnownType(typeof(Failure<Patient>)]
public Fallible<Patient> GetPatient(int id) {
  return new Success<Patient>(new Patient {ID = 1,FirstName = "Jim",Surname = "Spriggs"});
}

虽然每次调用都必须添加四个属性很痛苦,但它确实有效。我想知道是否有办法将它们组合成一个属性,但至少我现在有一个可用的服务。

希望这对某人有所帮助。