WCF DTO中的接口
本文关键字:接口 DTO WCF | 更新日期: 2023-09-27 17:59:56
我尝试传输一个DTO(WCF客户端到WCF服务器),其中包含一个带接口的子对象。
我的代码:
WCF服务方法:
[OperationBehavior(TransactionScopeRequired = true)]
public void SendTest(MyTestDto testDto)
{
...
}
MyTestDto类:
[Serializable]
[DataContract(Name = "MyTestDto")]
public class MyTestDto : ITestDto
{
[DataMember(IsRequired = true, Order = 1, Name = "MyTestDto")]
[DataMemberValidation(IsRequired = true)]
public ITest Test { get; set; }
}
ITest接口:
public interface ITest
{
int Field1 {get;set;}
int Field2 {get;set,}
}
问题是,如果我将MyTestDto从服务器传输到客户端,我总是会得到一个FaultException
。我分析了WSDL文件,测试字段的类型为:AnyType
。我认为,这就是问题所在。我已经用一个抽象类替换了ITest
,因此通信工作正常(当然,我必须用抽象类设置ServiceKnownType
属性)。
你能帮我吗?为什么它与抽象类一起工作而不与接口一起工作?
WCF使用具体类型,接口不能在WCF上序列化。
只有在使用ServiceKnownType
标记服务或使用KnownType
属性标记数据契约的情况下,才能使接口成为抽象类。下面是一个例子;
public abstract Test
{
public int Field1 {get;set;}
public int Field2 {get;set,}
}
public class SomeTest : Test
{
...
}
[ServiceKnownType(typeof(SomeTest))]
public class SomeService : ISomeService
{
public void SendTest(Test test)
}