我们使用 C# 代码使用 WCF 服务。通过右键单击“添加服务引用”并将其指向 WSDL,在 Visual Studio 中生成客户端。
最近,WCF 提供程序向其序列化的对象之一添加了一些属性。该类(class)来自
public class MyClass
{
public string Foo { get; set; }
public string Baz { get; set; }
public string Zed {get; set; }
}
对此:
public class MyClass
{
public string Foo { get; set; }
public string Bar { get; set; } //<= New Property
public string Baz { get; set; }
public string Zed {get; set; }
}
就我们而言,这导致 Baz
和 Zed
在反序列化时突然开始为 null,直到我们更新服务引用。事实上,真实对象在 Bar
之后按字母顺序排列大约有 20 个属性,并且它们全部为 null(对于整数为 0
,对于 bool 值为 false
等)。
反序列化失败的方式似乎很奇怪。它没有抛出异常或忽略它一无所知的新属性......它只是将新属性反序列化为默认值后按字母顺序出现的每个属性。
所以我的问题是,这是怎么回事以及如何防止它?最好,我希望客户端进行某种设置,告诉它“忽略新属性”,但告诉服务提供商如何防止 future 发生重大更改也可以。
最佳答案
MSDN has an article其中列出了数据成员的序列化顺序。该文档的一个要点是:
current type’s data members that do not have the Order property of the DataMemberAttribute attribute set, in alphabetical order.
因此,如果您添加一个新属性,而没有 DataMemberAttribute 的 Order 属性,则该属性将按字母顺序排序。
基于discussion here ,您唯一的选择是:
- 将序列化器更改为其他内容
- 确保 XML 中元素的顺序与属性的顺序匹配。也许您始终可以使用 DataMemberAttribute 的 Order 属性?
关于c# - 在 WCF 服务中向对象添加属性会破坏客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34357646/