使用DataContractSerializer时,我发现了一些异常行为。我已经定义了一个消息合同:
namespace MyNamespace.DataContracts
{
[MessageContract(WrapperName = "order", WrapperNamespace = @"http://example.com/v1/order")]
public class MyOrder
{
[MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 1)]
public MyStore store;
[MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 2)]
public MyOrderHeader orderHeader;
[MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 3)]
public List<MyPayment> payments;
[MessageBodyMember(Namespace = @"http://example.com/v1/order", Order = 4)]
public List<MyShipment> shipments;
}
.
.
我发送的XML消息如下:
<?xml version="1.0" encoding="utf-8"?>
<order xmlns="http://example.com/v1/order>
<store>
...
</store>
<orderHeader>
...
</orderHeader>
<payments>
<payment>
...
</payment>
</payments>
<shipments>
<shipment>
...
</shipment>
</shipments>
</order>
我的服务按预期反序列化此XML。在我的服务中,我正在使用DataContractSerializer来创建一个XML字符串,这就是事情变得奇怪的地方。我正在使用这样的序列化器:
DataContractSerializer serializer = new DataContractSerializer(typeof(MyOrder));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, order);
ms.Position = 0;
StreamReader sr = new StreamReader(ms);
string outputMessage = sr.ReadToEnd();
}
完成后,outputMessage包含以下XML:
<?xml version="1.0" encoding="utf-8"?>
<MyOrder xmlns="http://example.com/v1/order" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<order>
<store>
...
</store>
<orderHeader>
...
</orderHeader>
<payments>
<payment>
...
</payment>
</payments>
<shipments>
<shipment>
...
</shipment>
</shipments>
</order>
</MyOrder>
毋庸置疑,任何期望接收原始XML消息的内容都无法解析此问题。所以我想我有两个问题:
感谢。
我应该在.NET 4中添加它。
答案 0 :(得分:0)
您可以尝试使用WriteObjectContent
代替WriteObject
,但我无法使用您提供的代码重现您的问题。在我的定义中,作为消息合同一部分的所有额外类定义都是空的,但这是我得到的XML:
<MyOrder xmlns="http://schemas.datacontract.org/2004/07/SandboxApp"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<orderHeader i:nil="true"/>
<payments i:nil="true"/>
<shipments i:nil="true"/>
<store i:nil="true"/>
</MyOrder>
这似乎很奇怪,因为它似乎忽略了WrapperName
。 .NET 3.5 SP1和.NET 4.0中的结果相同。