【问题标题】:Covariance implementaion in WCF rest serviceWCF 休息服务中的协方差实现
【发布时间】:2011-06-18 11:51:43
【问题描述】:

协方差的概念能否在WCF的rest服务中实现,

即,我有类 A 和 B 继承自它。

WCF 操作合约有输入参数 A。我应该能够将 B 也传递给这个操作。

我有一个访问我的 EXF 休息服务的 JSON 客户端。

我是否有可能实现协方差概念。我应该如何在服务器和客户端中执行此操作。请帮忙。

【问题讨论】:

    标签: wcf wcf-rest


    【解决方案1】:

    当然!要使其工作,唯一需要做的就是将 B 类添加到服务应该使用 ServiceKnownType 属性知道的类型列表中。

    下面是我整理的一个简单示例来演示这一点,假设这是您的服务合同:

    using System.Runtime.Serialization;
    using System.ServiceModel;
    
    namespace WcfCovariance
    {
        [ServiceKnownType(typeof(Employee))]
        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            Person GetPerson();
    
            [OperationContract]
            Person PutPerson(Person person);
        }
    
        [DataContract]
        public class Person
        {
            [DataMember]
            public string Name { get; set; }
        }
    
        [DataContract]
        public class Employee : Person
        {
            [DataMember]
            public double Salary { get; set; }
        }
    }
    

    以及实现:

    namespace WcfCovariance
    {
        public class Service1 : IService1
        {
            static Person Singleton = new Person { Name = "Me" };
    
            public Person GetPerson()
            {
                return Singleton;
            }
    
            public Person PutPerson(Person person)
            {
                Singleton = person;
    
                return Singleton;
            }
        }
    }
    

    因为您已经使用 ServiceKnownType 属性告诉 WCF 关于类型 Employee,所以当遇到它时(在输入参数和响应中),它将能够对其进行序列化/反序列化,无论是使用 JSON与否。

    这是一个简单的客户端:

    using System;
    using WcfCovarianceTestClient.CovarianceService;
    
    namespace WcfCovarianceTestClient
    {
        class Program
        {
            static void Main(string[] args)
            {
                var client = new Service1Client("WSHttpBinding_IService1");
    
                // test get person
                var person = client.GetPerson();
    
                var employee = new Employee { Name = "You", Salary = 40 };
                client.PutPerson(employee);
    
                var person2 = client.GetPerson();
    
                // Employee, if you add breakpoint here, you'd be able to see that it has all the correct information
                Console.WriteLine(person2.GetType()); 
    
                Console.ReadKey();
            }
        }
    }
    

    将子类型传入和传出 WCF 服务是很常见的,但您唯一不能做的就是在合同中指定一个接口作为响应。

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-10
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 2012-03-08
      • 1970-01-01
      相关资源
      最近更新 更多