Wcf 方法接口作为参数在客户端被视为对象
Wcf method interface as parameter seen as object on clientside
我在 OperationContract 中使用接口作为输入参数。但是当我在客户端生成代理 class 时,客户端方法被视为:GetDat(object value) 而不是 GetData(IMyObj value)
- 服务接口
[ServiceContract]
[ServiceKnownType(typeof(MyObj))]
public interface IService
{
[OperationContract]
string GetData(IMyObj value);
}
- 服务class
public class Service : IService
{
public string GetData(IMyObj value)
{
return string.Format("You entered: {0}", value.MyValue);
}
}
- 界面
public interface IMyObj
{
int MyValue { get; set; }
}
- 数据合同
[DataContract]
[KnownType(typeof(IMyObj))]
public class MyObj : IMyObj
{
[DataMember]
public int MyValue { get; set; }
}
注意:关于接口参数和wcf,Whosebug上有很多类似的问题。但他们都告诉使用 ServiceKnownType 属性和 KnownTypeAttribute (我这样做了)。但是它仍然给客户端的调用方法一个对象作为参数类型而不是我的接口类型。
上找到了 Ladislav 的回答
Hello,
you can't do that. DataContract represents definition of data
transfered between client and service. This definition is transformed
into XSD which describes format of exchanged XML (serialized data
contract object). XML can transfer only data not logic and it doesn't
transfer any inormation about data contract implementation = no
inheritance and no interface implementation. If you want to use
datacontract with interface on the client you have to share that data
contract in assembly (not only the interface) and reuse it on the
client when service proxy is generated.
Best regards, Ladislav
我在 OperationContract 中使用接口作为输入参数。但是当我在客户端生成代理 class 时,客户端方法被视为:GetDat(object value) 而不是 GetData(IMyObj value)
- 服务接口
[ServiceContract] [ServiceKnownType(typeof(MyObj))] public interface IService { [OperationContract] string GetData(IMyObj value); }
- 服务class
public class Service : IService { public string GetData(IMyObj value) { return string.Format("You entered: {0}", value.MyValue); } }
- 界面
public interface IMyObj { int MyValue { get; set; } }
- 数据合同
[DataContract] [KnownType(typeof(IMyObj))] public class MyObj : IMyObj { [DataMember] public int MyValue { get; set; } }
注意:关于接口参数和wcf,Whosebug上有很多类似的问题。但他们都告诉使用 ServiceKnownType 属性和 KnownTypeAttribute (我这样做了)。但是它仍然给客户端的调用方法一个对象作为参数类型而不是我的接口类型。
Hello,
you can't do that. DataContract represents definition of data transfered between client and service. This definition is transformed into XSD which describes format of exchanged XML (serialized data contract object). XML can transfer only data not logic and it doesn't transfer any inormation about data contract implementation = no inheritance and no interface implementation. If you want to use datacontract with interface on the client you have to share that data contract in assembly (not only the interface) and reuse it on the client when service proxy is generated.
Best regards, Ladislav