如何反序列化自定义对象列表

时间:2013-03-18 22:46:28

标签: c# .net wcf asp.net-3.5

我确实遇到了试图通过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);

1 个答案:

答案 0 :(得分:1)

假设您的客户端是.NET 3.5应用程序并且FooReportRecord位于.NET 4 wcf库中,则会出现编译时错误。

将FooReportRecord移动到在.NET 3.5中编译的第3类库,并从WCF应用程序和客户端(ASP.NET)引用它

但正如@Phil所提到的,为什么不返回FooReportRecord []而不是byte []

<强>服务

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");