2012-01-26 57 views
0

我在使用WCF Web API 0.6.0在HttpResponseMessage內返回List<T>IList<T>有一些問題。WCF Web API序列化問題

我的簡單的服務合同是:

[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.HttpResponseMessage 1[System.Collections.Generic.IList 1 [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 ...

+0

爲什麼你想返回包裝在HttpResponseMessage中的列表?你不能只是返回列表,而不是HttpResponseMessage > – Rajesh

回答

2

不要在WCF方法返回的IList。如何返回包裝List的HttpResponseMessage?

[編輯]

在第二次看問題不IList的,它與HttpResponseMessage類。它不是可序列化的。

+0

我試過在HttpResponseMessage中返回列表和PersonCollection,都給出相同的錯誤。 –

1

我已經使用IEnumerable來完成相同的任務。它像魅力一樣...