【问题标题】:WCF Service and Interface - the result is object, even though ServiceKnownType was usedWCF 服务和接口 - 结果是对象,即使使用了 ServiceKnownType
【发布时间】:2010-05-12 04:45:57
【问题描述】:

我需要将一些与 Silverlight 不兼容的对象转换为模型以通过 WCF 服务发送。我尝试使用 ServiceKnownType,但结果仍然是对象。检索结果后,我可以将对象转换为模型,但我不想每次都这样做。这是我尝试过的一个示例。

这是一个好方法吗?为什么 WCF 不将 BikeModel 作为对象返回。

界面

public interface IBike
{
  string BikeName { get; set;}
}

型号

[DataContract]
public class BikeModel : IBike
{
  [DataMember]
  public string BikeName { get; set; }
}

由于基类中的 MarshalObjectByRef 等而无法在 Silverlight 中使用的其他对象

public class Bike : IBike, UnusableBaseClass
{
....
}

IService1

[ServiceContract]
[ServiceKnownType(typeof(BikeModel))]
public interface IService1
{
    [OperationContract]
    IBike GetBike();
}

服务

 public class Service1 : IService1
 {
   public IBike GetBike()
   {
     Bike b = BikeManager.GetFirstBikeInTheDataBase();
     return b;
    }
 }

MainPage.xaml.cs -

public MainPage()
{
  InitializeComponent();
  this.Loaded += (s, a) =>
  {
     ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
     client.GetBikeCompleted += (sender, e) =>
     {
        var d = e.Result;
        // this cast works
        BikeModel model = (BikeModel)d;
      };
      client.GetBikeAsync();

    };
}

【问题讨论】:

    标签: silverlight wcf


    【解决方案1】:

    这只是一个错字,还是在你的模型中真的像这样??模型类应该用[DataContract] 装饰,而不是[DataMember]。应该是这样的:

    [DataContract]
    public class BikeModel : IBike
    {
      [DataMember]
      public string BikeName { get; set; }
    }
    

    更新:好的,这只是一个错字。

    你可以试试这个吗?将您的IBike 接口转换为BaseBike 基类:

    public class BaseBike
    {
      string BikeName { get; set;}
    }
    

    然后从您的调用中返回该基本类型

    [ServiceContract]
    [ServiceKnownType(typeof(BikeModel))]
    public interface IService1
    {
        [OperationContract]
        BaseBike GetBike();
    }
    

    这有什么改变吗?我知道 WCF 对可以序列化的内容有点挑剔——因为所有序列化的内容都必须在 XML 模式中表示,因此您不能轻易使用接口和/或泛型。

    您可以尝试的另一个选项是在操作上使用更集中的[KnownType] 属性,而不是[ServiceKnownType]。再一次 - 不确定它是否有帮助,我在这里寻找想法......(从 .NET 的角度来看,你的东西看起来不错 - 但 WCF 通信并不总是完全相同的世界......)

    【讨论】:

    • 我刚刚检查了我的代码,它是 DataContract,所以这是一个错字。我已经编辑了我的帖子来修复它。谢谢。
    • 更改为基本类型导致服务返回 BaseBikeModel 的结果。不幸的是,由于需求等原因,我无法更改 Bike 对象的基类。我尝试将 [KnownType(typeof(IBike))] 放在 BikeModel 上,但没有任何运气。没错,WCF 并不总是按预期的方式工作。
    • @Kevin:抱歉,我的意思是尝试将 [KnownType(typeof(BikeModel))] 放到返回 IBike 的操作中。它已经返回 IBike - 所以你不需要再次将它作为额外的“已知类型”
    • KnownType属性必须放在一个类上(特定方法上面会导致编译器错误),所以我在Service1类上试了一下,也遇到了同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多