【发布时间】:2014-05-16 20:08:30
【问题描述】:
我在尝试调用 WCF 服务时收到此错误:
格式化程序在尝试反序列化 消息:尝试反序列化参数时出错 http://tempuri.org/:ResultValue。 InnerException 消息是“错误” 在第 1 行位置 1741. 元素 'htp://schemas.microsoft.com/2003/10/Serialization/Arrays:anyType' 包含映射到名称的类型的数据 'htp://schemas.datacontract.org/2004/07/DataAccess:Person'。 反序列化器不知道映射到此名称的任何类型。 考虑使用 DataContractResolver 或添加对应的类型 'Person' 到已知类型列表 - 例如,通过使用 KnownTypeAttribute 属性或通过将其添加到已知类型列表中 传递给 DataContractSerializer。'。
我有一个具有以下定义的接口项目:
public interface IPerson
{
string Name { get; set; }
}
public interface IPersonExtended : IPerson
{
// If I remove the List of IPerson property, it works fine
List<IPerson> Contacts { get; set; }
}
我有一个实现接口的 DataAccess 项目:
public class Person : IPerson
{
public string Name { get; set; }
}
public class PersonExtended : IPersonExtended
{
public string Name { get; set; }
private List<IPerson> mContacts = new List<IPerson>();
// If I remove the List of IPerson property, it works fine
public List<IPerson> Contacts
{
get { return mContacts; }
set { mContacts = value; }
}
}
我的服务合同如下所示:
[ServiceContract]
[ServiceKnownType(typeof(Person))]
[ServiceKnownType(typeof(PersonExtended))]
public interface IMyService
{
[OperationContract]
ServiceCallResult<GetPeopleResponse> GetPeople(GetPeopleRequest request);
}
我的服务看起来像:
public class MyService : IMyService
{
public ServiceCallResult<GetPeopleResponse> GetPeople(GetPeopleRequest request)
{
GetPeopleResponse response = new GetPeopleResponse();
// Get Some people that have contacts
response.People = GetPeopleFromSomewhere();
ServiceCallResult<GetPeopleResponse> result =
new ServiceCallResponse<GetPeopleResponse> { ResultValue = response };
return result;
}
}
我的响应对象看起来像:
[DataContract]
[KnownType(typeof(PersonExtended))]
[KnownType(typeof(Person))]
[KnownType(List<Person>))]
[KnownType(List<PersonExtended))]
public class GetPeopleResponse
{
[DataMember]
public List<PersonExtended> People { get; set; }
}
Response 对象只是包装在一个包含状态信息等的MessageContract 对象中。
编辑 如果我在整个工作流程中删除联系人(列表)属性,它工作正常。我想知道它是否与尝试使用带有接口列表而不是具体对象的属性有关,但我不确定如何在不添加循环引用的情况下通过我的项目结构解决这个问题。
【问题讨论】: