0

我正在开发一个 WebService 客户端,并且在派生类型序列化方面遇到了一些问题。

请求类

[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 类和派生类型

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

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

结果 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>

我必须更改什么才能正确序列化派生类?

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

提前致谢。

4

1 回答 1

0

它是如此简单:您应该KnownType像这样向基类添加属性:

[DataContract]
[KnownType(typeof(TestRequest))]
public abstract class ServiceObject
{ }
于 2017-04-13T10:54:00.377 回答