Missing subclass field in WCF - attempt to get polymorphism

First of all, keep in mind that I followed this question on Google. I use WCF to expose some services. I have something like:

 [DataContract] [KnownType(typeof(Sub))] public class Base { [DataMember] public int base; } [DataContract] public class Sub : Base { [DataMember] public int sub; } [ServiceContract] [ServiceKnownType(typeof(Sub))] public interface IServices { [OperationContract] public void test(Base b); } 

I would like to be able, like XML, to send Sub and Base objects. When I break with the debugger in the first line of test(Base b) in b , I do not see the Sub field.

The problem is this:

 <?xml version="1.0"?> <soapenv:Envelope xmlns:xs="http://www.w3.org/2003/05/soap-envelope/" soapenv:encodingStyle="http://www.w3.org/2003/05/soap-encoding"> <soapenv:Header/> <soapenv:Body> <xs:test> <xs:b> <xs:base>123</xs:base> <xs:sub>1234</xs:sub> </xs:b> </xs:test> </soapenv:Body> </soapenv:Envelope> 

This XML was successfully deserialized, but in the object I see only the Base field (equal to 123 ), however I do not see the Sub field.
Where am I mistaken?

0
source share
2 answers

First, your classes do not inherit from each other. I assume that the base should be the base class sub? You need to fix this first.

Then the foo method must be virtual in order to be overridden in sub. Correct the following.

Last but not least, WCF does not tolerate methods. It only transfers data.

If you need executable code, put it in other classes. This is very confusing for users and for yourself when you are tempted to think that your class will actually be passed. This is not true. Only data.

0
source

As I understand it, you want to manually send the correct XML to your service and make it recognize the subobject. In my comments on your question, I mentioned a KnownTypes detection approach, but it solves other problems.

Your current C # code looks fine, but some type attributes are missing from XML. It should look like this:

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wcf="http://schemas.datacontract.org/2004/07/<PUT THE C# NAMESPACE OF YOUR ENTITIES HERE>"> <soapenv:Header/> <soapenv:Body> <tem:Test> <tem:b xsi:type="wcf:Sub"> <wcf:base>1</wcf:base> <wcf:sub>2</wcf:sub> </tem:b> </tem:Test> </soapenv:Body> </soapenv:Envelope> 

I just tested it and it did a great job with the WCF project created with VS 2015 and tested with SoapUI. Both sub and base values โ€‹โ€‹reached the test method, and the Sub entity was available inside it.

A similar question in StackOverflow with the same xsi: type type solution is also listed here .

If this does not help, I can download the demo project somewhere on GitHub.

0
source

All Articles