WCF傳輸泛型 List 對象 轉

來源:互聯網
上載者:User

http://www.cnblogs.com/WizardWu/archive/2009/08/09/1542102.html

 

在 WCF 中,在 Server-side 和 Client-side 之間,傳遞預設無法傳輸的 List<T>、List<自訂類> 等類型的對象,以及傳遞 Dictionary 等泛型 Collection 對象。本帖並無高來高去的高深技術,但版工我認為本帖的小技巧實用性很高,而且是每個學習 WCF 的人都一定會遇到的問題,因此鬥膽將本文發在部落格園首頁。

--------------------------------------------------------
本帖的樣本下載點:
http://files.cnblogs.com/WizardWu/090809.zip

執行樣本需要 Visual Studio 2008 + SP1,不需要資料庫。
若您下載後,在 VS 2008 裡按 F5 時項目無法正常執行,請留言告知。
--------------------------------------------------------

在編程時,DataSet、DataTable,以及 List、Dictionary 等 Collection 類型常會使用到。在 .NET Web Service 和 WCF 中,伺服器端函數 (Operation) 的傳回型別,若為 DataSet、DataTable,則用戶端可直接調用 (若用戶端程式也是 .NET 的話);但在 WCF 中,VS 2008 預設的配置,並無法傳輸 List<string>、List<自訂類> 等類型的對象,而泛型的 Dictionary 對象卻可以。

[註:Method、Operation 中文都叫做「方法」,但前者是存在 OO 中的類,不存在網路上;後者存在於 Service 中,公開在網路上可供其他程式調用。WCF、Data Services 和 RIA Services 中公開在網路上的函數和方法,都可稱作 Operation。]

關於這點,小弟我查了微軟 MCTS 認證 WCF 3.5 的官方用書 [10]、O'Reilly 的書籍 [11],都未提到如何解決,書中只提到 .NET collections 的 metadata,以 WSDL 在網路上傳輸時,會以「數組 (array)」的格式呈現。

Because .NET collections are .NET-specific, WCF cannot expose them in the service metadata, yet because they are so useful, WCF offers dedicated marshaling rules for collections.

Whenever you define a service operation that uses the collection interfaces IEnumerable<T>, IList<T>, or ICollection<T>, the specific collection-type information gets lost in the metadata (WSDL) export, so in terms of how collection types are sent across the wire, they all are represented as arrays, the resulting metadata always uses an array.

 

開發 WCF 時,若 VS 2008 都用預設配置,則當 WCF 的伺服器端函數 (Operation) 的傳回型別為 List<string> 時,實際返回的類型為 string[] 數組,因此用戶端若仍用 List<string> 的變數去接收和賦值時,在編譯時間期,即會發生 1 的轉型錯誤:


圖 1 List 資料結構還原序列化後,在用戶端自動變成了數組

後來我在網路上發現兩篇博文 [1], [2],提到只要更改 VS 2008 中,WCF 用戶端程式「加入服務參考 (Add Service Reference)」的設定即可處理此種需求。做法如下:

請參閱本帖的下載樣本。當我們的用戶端程式,要引用網路上既有的 WCF 服務契約時,我們會如 2 般,添加一個 service proxy reference。


圖 2 在 ASP.NET 用戶端程式中引用 WCF Service 

在 3 的「加入服務參考」表單中,右上方的「前往」按鈕,是要查看網路上某個 IP 和連接埠的 WCF Service;右邊的「發現」按鈕,是要查看和此用戶端項目,位於同一個 VS 2008 解決方案裡的 WCF Service。此時我們單擊表單左下方的「進階」按鈕。


圖 3 在此窗格裡輸入正確的中繼資料交換地址,會自動取得 WCF Service 的 Operation 名稱

如 4,我們在「集合類型」下拉式功能表中,把預設的 System.Array 改成我們想使用的 Generic.List 類型;而另一個「字典集合類型」下拉式功能表則保持不變,表示此 WCF Service 可在網路上傳輸泛型的 Dictionary 類型對象。


圖 4 預設的集合類型為 System.Array

微軟的 VS 預設會這樣設定,可能如同博文 [2] 所提到的,WCF 的用戶端可能是舊版 .NET 1.x 版的環境,也可能是 Java 或其他各種非微軟的技術平台,因此 VS 2008 預設選用所有廠商、所有平台都支援的 Array 數組,作為網路傳輸的類型,而非最新版 .NET 平台特有的 Collection 資料結構。

最後,若使用者端程式要再更改配置,只要如 5 般,在 VS 項目裡既有的 Reference 上,選擇「佈建服務引用」即可。


圖 5 在 ASP.NET 用戶端程式中,修改已引用的 WCF Service

以下為本帖下載樣本的代碼。我們在伺服器端的 WCF Service,提供三個傳回型別分別為 List<string>、List<自訂類>、Dictionary<string,string> 的函數,給 WCF 用戶端 ASP.NET 程式調用,執行結果如 6。

 

Server-side/IService.cs

 

 

Server-side/Service.cs

 

Client-side/Default.aspx.cs

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ServiceReference1.ServiceClient prox = new ServiceReference1.ServiceClient();

        /*********** List<string> ***********/
        //string[] list1 = new string[2];   //未改設定前,Server 返回的 List<string>,Client 只能取得 string 數組
        List<string> list1 = new List<string>();        
        list1 = prox.getListString();

        Response.Write(list1[0] + "<br>");
        Response.Write(list1[1] + "<p>");

        /*********** List<自訂類> ***********/
        List<ServiceReference1.Employee> list2 = new List<ServiceReference1.Employee>();
        list2 = prox.getListEmployee();
        
        Response.Write(list2[0].name + "<br>");
        Response.Write(list2[0].age + "<br>");
        Response.Write(list2[0].oooo + "<p>");      //object 類型

        /*********** Dictionary<string,string> ***********/
        Dictionary<string, string> dict1 = new Dictionary<string, string>();
        dict1 = prox.getDictionaryString();

        foreach (KeyValuePair<string, string> kvp in dict1)
        {
            Response.Write(kvp.Key + ", " + kvp.Value + "<br>");
        }
    }
}

複製代碼

 

 


圖 6 本帖樣本執行結果,從 WCF Service 返回 List<string>、List<自訂類>、泛型 Dictionary 三種類型的變數

 

若有興趣實作,但對 WCF 還不熟的網友,可參考下方參考檔案 [8], [9],有提供快速入門的教學。

--------------------------------------------------------

相關文章:

[1] Using Generic List<T> From WCF Services
http://dotnet.org.za/hiltong/archive/2008/05/21/using-generic-list-lt-t-gt-from-wcf-services.aspx

[2] WCF Data Contract對Collection和Dictionary的支援
http://www.cnblogs.com/artech/archive/2007/11/27/974665.html

[3] WCF分布式開發步步為贏(8):使用資料集(DataSet)、資料表(DataTable)、集合(Collection)傳遞資料
http://www.cnblogs.com/frank_xl/archive/2009/04/23/1437486.html

[4] WCF技術剖析之十三:序列化過程中的已知類型(Known Type)
http://www.cnblogs.com/artech/archive/2009/07/12/1521994.html

[5] Trouble getting a WCF return a collection to a .NET 2.0 client
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/3749248c-c3b0-40eb-88db-95574205dd9a

[6] Collection Types in Data Contracts
http://msdn.microsoft.com/zh-cn/library/aa347850.aspx
http://msdn.microsoft.com/en-us/library/aa347850.aspx

[7] Sharing WCF Collection Types between Service and Client
http://www.codeproject.com/KB/WCF/WCFCollectionTypeSharing.aspx

[8] Step-By-Step教學(10):將檔案類型 WCF 服務部署到 IIS (繁體中文, 與本帖無直接關係)
http://vmiv.blogspot.com/2008/05/step-by-step10wcfiis.html

[9] WCF學習----我的第一個WCF程式 (與本帖無直接關係)
http://www.cnblogs.com/ASPNET2008/archive/2008/06/01/1211613.html

--------------------------------------------------------

相關書籍:

[10] Microsoft .NET Framework 3.5-Windows Communication Foundation, MCTS EXAM 70-503 Training Kit, Chapter 1
http://www.microsoft.com/learning/en/us/Books/12486.aspx
http://www.amazon.com/MCTS-Self-Paced-Training-70-503-PRO-Certification/dp/0735625654

[11] Programming WCF Services, 2nd Edition, Juval Löwy, Chapter 3
WCF服務編程, Juval Löwy 著, 中文版本由「張逸、徐寧」翻譯。
http://oreilly.com/catalog/9780596521301/

--------------------------------------------------------

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.