【问题标题】:WCF Web API serialization issueWCF Web API 序列化问题
【发布时间】:2012-02-19 12:40:49
【问题描述】:

我在使用 WCF Web API 0.6.0 在 HttpResponseMessage 中返回 List<T>IList<T> 时遇到一些问题。

我的简单服务合同是:

[ServiceContract]
public interface IPersonService
{
    [OperationContract]
    [WebInvoke(UriTemplate = "people", Method = "GET")]
    HttpResponseMessage<IList<Person>> LoadPeople();
}

实现是:

public class PersonService : IPersonService
{
    public HttpResponseMessage<IList<Person>> LoadPeople()
    {
        var people = new List<Person>();
        people.Add(new Person("Bob"));
        people.Add(new Person("Sally"));
        people.Add(new Person("John"));
        return new HttpResponseMessage<IList<Person>>(people);
    }
}

而 Person 类是这样的:

[DataContract]
public class Person
{
    public Person(string name)
    {
        Name = name;
    }

    [DataMember]
    public string Name { get; set; }
}

但是当我调用该方法时,我得到了以下异常:

System.Runtime.Serialization.InvalidDataContractException:无法序列化类型“System.Net.Http.HttpResponseMessage1[System.Collections.Generic.IList1[Person]]”。考虑使用 DataContractAttribute 属性对其进行标记,并使用 DataMemberAttribute 属性标记您想要序列化的所有成员。如果该类型是一个集合,请考虑使用 CollectionDataContractAttribute 对其进行标记。有关其他支持的类型,请参阅 Microsoft .NET Framework 文档。

显然,序列化 IList 存在问题。我的 Person 类已经指定了 DataContract 和 DataMember 属性,所以我翻阅了一下,发现你不能序列化接口。

我尝试将集合的类型从 IList 更改为 List,但仍然返回相同的错误。

我什至尝试过创建一个 PersonCollection 类,并按照推荐使用 CollectionDataContract 属性对其进行标记:

[CollectionDataContract]
public class PersonCollection : List<Person>
{
}

但这仍然不起作用,返回完全相同的错误。阅读更多内容后,我发现this bug 标记为已关闭(无法修复)。

谁能帮忙,或者提供一个合适的替代方法?非常感谢。

更新

在遇到很多奇怪的问题后,我对代码进行了重大重构,问题似乎已经消失了。我现在返回一个包装 IList 的 HttpResponseMessage,它工作正常。

感谢您提供的所有帮助,但我相信我可能一直在查看 Heisenbug...

【问题讨论】:

  • 为什么要返回包裹在HttpResponseMessage中的List?你能不能只返回 List 而不是 HttpResponseMessage>

标签: .net wcf serialization datacontract


【解决方案1】:

我已将 IEnumerable 用于相同的任务。它就像魅力一样......

【讨论】:

    【解决方案2】:

    不要在 wcf 方法中返回 IList。用 List 包裹返回 HttpResponseMessage 怎么样?

    [编辑]

    再看问题不在于 IList,而在于 HttpResponseMessage 类。而且它不可序列化。

    【讨论】:

    • 我尝试在 HttpResponseMessage 中同时返回 List 和 PersonCollection,都给出了相同的错误。
    猜你喜欢
    • 2012-03-19
    • 2016-12-11
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多