【问题标题】:Silverlight serialization of a .NET Web service causes XML error.NET Web 服务的 Silverlight 序列化导致 XML 错误
【发布时间】:2010-10-23 15:38:45
【问题描述】:

我有这个类由 Web 服务提供,然后由 Silverlight 应用程序使用(我不知道这是否相关)

[Serializable]
public class Entry
{
    private string _title;

    public string Id { get; set; }
    public string Title { get { return _title; } set { _title = value; } }
    public string Link { get; set; }
    public DateTime Published { get; set; }
    public DateTime Updated { get; set; }
    public User User { get; set; }
    public Service Service { get; set; }
    public List<Comment> Comments { get; set; }
    public List<Like> Likes { get; set; }
    public List<Media> Media { get; set; }
}

我添加了_title 变量来演示出了什么问题。当我在 silverlight 应用程序中引用 Web 服务时,它会生成以下 xsd:

  <xs:complexType name="Entry">
    <xs:sequence>
      <xs:element name="_title" nillable="true" type="xs:string" />
      <xs:element name="_x003C_Comments_x003E_k__BackingField" nillable="true" type="tns:ArrayOfComment" />
      <xs:element name="_x003C_Id_x003E_k__BackingField" nillable="true" type="xs:string" />
      <xs:element name="_x003C_Likes_x003E_k__BackingField" nillable="true" type="tns:ArrayOfLike" />
      <xs:element name="_x003C_Link_x003E_k__BackingField" nillable="true" type="xs:string" />
      <xs:element name="_x003C_Media_x003E_k__BackingField" nillable="true" type="tns:ArrayOfMedia" />
      <xs:element name="_x003C_Published_x003E_k__BackingField" type="xs:dateTime" />
      <xs:element name="_x003C_Service_x003E_k__BackingField" nillable="true" type="tns:Service" />
      <xs:element name="_x003C_Updated_x003E_k__BackingField" type="xs:dateTime" />
      <xs:element name="_x003C_User_x003E_k__BackingField" nillable="true" type="tns:User" />
    </xs:sequence>
  </xs:complexType>

注意只有title属性被简单命名,其他的被命名为&lt;Link&gt;_BackingField,当你尝试加载元素时它会完全消失,因为你不能在属性名称中包含。

为什么它序列化支持字段而不是公共属性?

【问题讨论】:

    标签: silverlight web-services serialization wcf-binding


    【解决方案1】:

    不要使用自动属性。 而不是写:

    public string Id { get; set; }
    

    写:

    string id;
    public string Id { get { return id;} set {id = value;} }
    

    在自动属性的情况下,只有支持字段会被序列化,这就是为什么你会得到奇怪的名字。

    【讨论】:

      【解决方案2】:

      this article 中所述,当您将DataContractSerializer(WCF 的默认序列化程序)与Serializable 属性结合使用时,行为是所有字段(公共和私有)都被序列化。因为在您的情况下支持字段是自动生成的,所以编译器会提供有趣的名称,这些名称不会与您可能创建的任何字段名称冲突(C# 可能不接受标识符中的“”,但 CLR没那么挑剔)。

      纠正这种情况的最简单方法可能是在 Entry 类中酌情添加 DataContractDataMember 属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-17
        • 1970-01-01
        相关资源
        最近更新 更多