简体   繁体   中英

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.

Everything works fine if I generate client from wsdl. Class is properly casted and serialized.

Problems happen when I try to use something external for example Postman from Chrome.

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.

It contains message type like this: 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. 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM