我们在我们的应用程序中为我们所有的响应 DTO 使用了一个基类。该类具有以下签名:
[Serializable]
public abstract class ResponseBase
{
public bool Successful { get; set; }
public List<ResponseMessage> Messages { get; set; }
//...Other code...
}
Messages 集合可以是以下任何一种类型:
[Serializable]
[XmlInclude(typeof(DebugMessage))]
[XmlInclude(typeof(InfoMessage))]
[XmlInclude(typeof(ValidationMessage))]
[XmlInclude(typeof(WarnMessage))]
[XmlInclude(typeof(RecoverableFaultMessage))]
[XmlInclude(typeof(FatalFaultMessage))]
public abstract class ResponseMessage
{
//..Other code...
}
具有以下具体版本:
[Serializable]
public class DebugMessage : ResponseMessage
{
public override MessageType MessageType { get { return MessageType.Debug; } }
}
[Serializable]
public class InfoMessage : ResponseMessage
{
public override MessageType MessageType { get { return MessageType.Info; } }
}
[Serializable]
public class ValidationMessage : ResponseMessage
{
public override MessageType MessageType { get { return MessageType.Validation; } }
}
[Serializable]
public class WarnMessage : ResponseMessage
{
public override MessageType MessageType { get { return MessageType.Warn; } }
}
[Serializable]
public class RecoverableFaultMessage : ResponseMessage
{
public override MessageType MessageType { get { return MessageType.RecoverableFault; } }
}
[Serializable]
public class FatalFaultMessage : ResponseMessage
{
public override MessageType MessageType { get { return MessageType.FatalFault; } }
}
所有 DTO 响应对象都从 ResponseBase 继承,但是即使在 WCF 合同上使用以下 ServiceKnownTypes
[ServiceKnownType(typeof(ResponseBase))]
[ServiceKnownType(typeof(ResponseMessage))]
[ServiceKnownType(typeof(List<ResponseMessage>))]
[ServiceKnownType(typeof(DebugMessage))]
[ServiceKnownType(typeof(InfoMessage))]
[ServiceKnownType(typeof(ValidationMessage))]
[ServiceKnownType(typeof(WarnMessage))]
[ServiceKnownType(typeof(RecoverableFaultMessage))]
[ServiceKnownType(typeof(FatalFaultMessage))]
[ServiceKnownType(typeof(List<DebugMessage>))]
[ServiceKnownType(typeof(List<InfoMessage>))]
[ServiceKnownType(typeof(List<ValidationMessage>))]
[ServiceKnownType(typeof(List<WarnMessage>))]
[ServiceKnownType(typeof(List<RecoverableFaultMessage>))]
[ServiceKnownType(typeof(List<FatalFaultMessage>))]
当我们将 Message 加载到 ResponseBase Messages 集合中时,会引发以下异常:
第 1 行位置 906 出错。元素“http://schemas.datacontract.org/2004/07/CX.Framework.Common.BaseTypes:ResponseMessage”包含映射到名称“http://schemas. datacontract.org/2004/07/CX.Framework.Common.BaseTypes:WarnMessage'。反序列化器不知道映射到此名称的任何类型。考虑使用 DataContractResolver 或将与“WarnMessage”对应的类型添加到已知类型列表中 - 例如,通过使用 KnownTypeAttribute 属性或将其添加到传递给 DataContractSerializer 的已知类型列表中。
我们在派生类型上完成了从 ServiceKnownType 到 XMLInclude 的所有工作。我对如何解决这个问题有点不知所措,希望任何人都能提供任何帮助。