[英]WCF Service with abstract class as method parameter
Here is example: 这是示例:
[ServiceKnownType("GetKnownTypes", typeof(Helper))]
[ServiceContract]
public interface ICommunicationService
{
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/SendMessage")]
string SendMessage(BusMessage message);
}
[DataContract]
[Serializable]
public abstract class BusMessage
{
[DataMember(Name = "uid")]
public string Id { get; set; }
}
GetKnownTypes returns all subtypes of BusMessage. GetKnownTypes返回BusMessage的所有子类型。
Everything works fine if I generate client from wsdl. 如果我从wsdl生成客户端,则一切正常。 Class is properly casted and serialized.
类已正确转换并序列化。
Problems happen when I try to use something external for example Postman from Chrome. 当我尝试使用外部物品(例如Chrome的Postman)时,会发生问题。
I receive an exception that abstract class cannot be instantiated. 我收到一个抽象类无法实例化的异常。
I noticed that field "__type" is added to json string while serializing from my client. 我注意到从客户端进行序列化时,字段“ __type”已添加到json字符串中。
It contains message type like this: BusTextMessage#namespace. 它包含如下消息类型:BusTextMessage#namespace。
I tried to add this manually as another field but it doesn't help. 我尝试将其手动添加为另一个字段,但没有帮助。 How to resolve problems like this?
如何解决这样的问题?
Shouldn't I use abstract class/interface as parameter? 我不应该使用抽象类/接口作为参数吗?
When you send "objects" to a WCF service, not the real object is sent, but the data is serialized and deserialized. 当您将“对象”发送到WCF服务时,不发送实际对象,而是对数据进行序列化和反序列化。 You can see this as the client only has a stub class without any methods and underlying logic when you import the service reference.
您可以看到,客户端在导入服务引用时只有一个存根类,没有任何方法和底层逻辑。
The client/service try to create instances of concrete classes and deserialize them from the data. 客户端/服务尝试创建具体类的实例,并从数据中反序列化它们。 As you can not create an instance of an abstract class, you can not "pass" an abstract class to a method call through WCF.
由于无法创建抽象类的实例,因此无法通过WCF将抽象类“传递”给方法调用。
In addition: The class being abstract does not really make sense, at least not in the example you're providing. 另外:抽象类实际上没有任何意义,至少在您提供的示例中没有意义。 As I said above, logic within data contract classes will not propagate to the client, so it's best to not have any logic (methods, complicated getters/setters) in them at all.
如前所述,数据协定类中的逻辑不会传播到客户端,因此最好根本没有任何逻辑(方法,复杂的获取器/设置器)。 If you mind that, there's no reason making the class
abstract
. 如果您介意的话,则无需将类
abstract
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.