协方差概念能否在 WCF 休息服务中实现,
即,我有 A 类和 B 类继承自它。
WCF 操作合同具有输入参数 A。我应该能够将 B 也传递给此操作。
我有一个访问我的 EXF 休息服务的 JSON 客户端。
我是否有可能实现协方差概念。我应该如何在服务器和客户端中执行此操作。请帮忙。
当然!唯一需要做的就是将 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;
}
}
}
因为您已经告诉 WCFEmployee
使用该ServiceKnownType
属性的类型,所以当遇到它(在输入参数和响应中)时,它将能够对其进行序列化/反序列化,无论是否使用 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 服务传递子类型和从 WCF 服务传递子类型是很常见的,但您唯一不能做的就是在合同中指定一个接口作为响应。
希望这可以帮助。