Merrin
Merrin

Reputation: 524

How to serialize derived types with WCF

I'm developing a WebService client and I'm having some problems with derived types serialization.

Request class

[MessageContract(WrapperName = "Request", WrapperNamespace = "http://www.test.com", IsWrapped = true)]
public class ServiceRequest
{
    [MessageHeader(Namespace = "http://www.test.com")]
    public AuthHeader AuthHeader { get; set; }

    [MessageBodyMember(Name = "Data", Order = 0)]
    public ServiceObject Request { get; set; }

    public ServiceRequest() { }

    public ServiceRequest(AuthHeader authHeader, ServiceObject request)
    {
        AuthHeader = authHeader;        
        Request = request;
    }
}

ServiceObject class and derived type

[XmlRoot(Namespace = "http://www.test.com")]
[XmlInclude(typeof(TestRequest))]
public abstract class ServiceObject
{ }

[XmlRoot(ElementName = "Test", Namespace = "http://www.test.com")]
public class TestRequest
{ }

Result XML

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:AuthHeader xmlns="http://www.test.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:h="http://www.test.com">
      <Username>TEST</Username>
      <Password>test</Password>
    </h:AuthHeader>
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Request xmlns="http://www.test.com">
      <Data xsi:type="TestRequest" />
    </Request>
  </s:Body>
</s:Envelope>

What do I have to change to properly serialize the derived class?

<Request xmlns="http://www.test.com">
    <Data>
       <Test/>
    </Data>
</Request>

Thanks in advance.

Upvotes: 0

Views: 189

Answers (1)

Mohammad
Mohammad

Reputation: 2764

its so simple: You should add KnownType attribute to your base class like this:

[DataContract]
[KnownType(typeof(TestRequest))]
public abstract class ServiceObject
{ }

Upvotes: 0

Related Questions