2013-03-18 121 views
3

我真的遇到了試圖通過WCF服務反序列化自定義對象列表的障礙。它使用.NET 4.我如何繞過不同的命名空間。我的ASP.NET應用程序在3.5上運行,參考設置正常。這可能是問題嗎?我如何解決它?如何反序列化自定義對象列表

我的服務就是建立這樣的:

合同

namespace MyDomain.Services.Report 
{ 
    [ServiceContract(Name = "ICompanyReport")] 
    public interface ICompanyReport 
    { 
     [OperationContract] 
     byte[] GetFooReport(string fooName); 
    } 

    [Serializable] 
    [DataContract(Name="FooReportRecord", Namespace="MyDomain.com"] 
    public class FooReportRecord 
    { 
     [DataMember] 
     public int ID {get; set;} 
     [DataMember] 
     public string Name {get; set;} 
    } 

} 

svc.cs

public class CompanyReport: ICompanyReport 
{ 
    public byte[] GetFooReport(string fooName) 
    { 
     var data = new List<FooReportRecord>(); 

     // get data based on fooName and populate data 

     var ms = new MemoryStream(); 
     var bf = new BinaryFormatter(); 
     bf.Serialize(ms, data); 
     return ms.ToArray(); 
    } 
} 

客戶端:

var ls = proxy.GetFooReport("bar"); 
var bf = new BinaryFormatter(); 
var ms = new MemoryStream(ls); 

// Unable to find assembly MyDomain.Services.Report error is thrown 
var reportData = (List<FooReportRecord>)bf.Deserialize(ms); 
+2

你爲什麼要返回byte []而不是FooReportRecord? – Phil 2013-03-18 22:54:01

+0

當您說「我的ASP.NET應用程序在3.5上運行」時,您的WCF服務託管在ASP.NET網站中嗎?或者ASP.NET應用程序是客戶端?我猜你在這裏的意思是客戶端 – EdmundYeung99 2013-03-18 23:20:14

+0

字節[]是儘量壓扁對象列表的嘗試。當我測試時,我可以使用字節數組與實際列表獲得更多結果。 – HapiDjus 2013-03-19 21:47:03

回答

1

假設您的客戶端是.NET 3.5應用程序,並且FooReportRecord位於.NET 4 wcf庫中,您將收到編譯時錯誤。

移動FooReportRecord到3號的類庫編譯.NET 3.5中和參考這個來自您的WCF應用程序和客戶端(ASP.NET)

但作爲@Phil提到的,爲什麼不回到FooReportRecord [],而不是字節[]

服務

public FooReportRecord[] GetFooReport(string fooName) 
{ 
    var data = new List<FooReportRecord>(); 

    // get data based on fooName and populate data 

    return data.ToArray(); 
} 

客戶

var proxy = new ServiceReference1.CompanyReportClient(); 
FooReportRecord[] ls = proxy.GetFooReport("bar"); 
+0

看完這一整天,我最終拋棄了將我的報告服務提升到4.0的全部理由。我返回的列表大小太大,無法嘗試一些黑客的跨版本反序列化。直到我看到「爲什麼字節[]」,它才讓我問自己同樣的問題。謝謝您的幫助! – HapiDjus 2013-03-19 21:50:14