将 属性 添加到 WCF 服务中断客户端中的对象

Adding Property to Object in WCF Service Breaks Client

我们使用 C# 代码使用 WCF 服务。通过右键单击 "Add Service Reference" 并将其指向 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; }
}

在我们这边,这导致 BazZed 在反序列化时突然开始为空,直到我们更新了服务引用。事实上,真实对象在 Bar 之后有大约 20 个按字母顺序排列的属性,它们都是空的(或者 0 表示整数,false 表示布尔值,等等)。

反序列化失败似乎是一种奇怪的方式。它没有抛出异常或忽略它一无所知的新属性……它只是使在新属性之后按字母顺序出现的每个 属性 反序列化为默认值。

所以我的问题是,这是怎么回事,我该如何预防?最好是,我想要某种设置让客户端告诉它"ignore new properties,",但告诉服务提供商他们如何防止未来的重大变化也很好。

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,您唯一的选择是:

  1. 将序列化程序更改为其他内容
  2. 确保 XML 中元素的顺序与您的属性的顺序相匹配。也许你总是可以使用 DataMemberAttribute 的 Order-属性?

确保你的 dll 是正确的,我在过去看到过一些非常奇怪的问题,其中服务的一侧指向过时的 dll

还记得the fundamentals of data contracts