我刚刚做了这个,我发现你需要在界面中添加 KnownTypesAttribute。
[ServiceContract]
[ServiceKnownType(typeof(MyContract1)]
[ServiceKnownType(typeof(MyContract2)]
[ServiceKnownType(typeof(MyContract3)]
public interface IMyService
{
[OperationContract]
object TakeMessage();
[OperationContract]
void AddMessage(object contract);
}
在您的实现中,您需要检查类型以确保它是您的 DataContract 之一。
编辑
如果你有很多合约,你可以使用反射将它们添加到 KnownTypes。
internal static class KnownTypeHelper
{
public static IEnumerable<Type> GetKnownTypes(ICustomAttributeProvider provider = null)
{
var types = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.Namespace == "Company.Path.To.DataContractsNamespace").ToArray();
return types;
}
}
然后你可以将你的接口声明为,
[ServiceContract]
[ServiceKnownType("GetKnownTypes", typeof(KnownTypeHelper))]
public interface IMyService
{
[OperationContract]
object TakeMessage( );
[OperationContract]
void AddMessage(object contract);
}
这是一种更清洁的方式。