我正在开发一个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>
提前致谢。
答案 0 :(得分:0)
非常简单:您应该将KnownType
属性添加到基类中,如下所示:
[DataContract]
[KnownType(typeof(TestRequest))]
public abstract class ServiceObject
{ }