【问题标题】:Problem using ReadAsDataContract using WCF REST Toolkit使用 WCF REST Toolkit 使用 ReadAsDataContract 时出现问题
【发布时间】:2011-08-23 04:38:46
【问题描述】:

我是序列化的新手,但遇到了问题。我有一个返回 IDDescriptionPair 对象数组的 REST 服务。使用服务时,我使用“将 XML 粘贴为类型”VS 插件来创建对象。我只是修改此对象以添加 DataContract 属性,以便我的命名空间在每一端都匹配。这是那个对象:

Imports System.Runtime.Serialization

<DataContract([Name]:="IDDescriptionPair", [Namespace]:="http://schemas.datacontract.org/2004/07/Blizzard.ClassLibrary")>
<System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.225"), _
 System.Diagnostics.DebuggerStepThroughAttribute(), _
 System.Xml.Serialization.XmlTypeAttribute([Namespace]:="http://schemas.datacontract.org/2004/07/Blizzard.ClassLibrary"), _
 System.Xml.Serialization.XmlRootAttribute   ([Namespace]:="http://schemas.datacontract.org/2004/07/Blizzard.ClassLibrary", IsNullable:=True)> _
Partial Public Class IDDescriptionPair

  Private descriptionField As String

  Private idField As Integer

  Private idFieldSpecified As Boolean

  '''<remarks/>
  <System.Xml.Serialization.XmlElementAttribute(IsNullable:=True)> _
  Public Property Description() As String
    Get
      Return Me.descriptionField
    End Get
    Set(value As String)
      Me.descriptionField = value
    End Set
  End Property

  '''<remarks/>
  Public Property ID() As Integer
    Get
      Return Me.idField
    End Get
    Set(value As Integer)
      Me.idField = value
    End Set
  End Property

  '''<remarks/>
  <System.Xml.Serialization.XmlIgnoreAttribute()> _
  Public Property IDSpecified() As Boolean
    Get
      Return Me.idFieldSpecified
    End Get
    Set(value As Boolean)
      Me.idFieldSpecified = value
    End Set
  End Property
End Class

我可以调用服务并反序列化对象,它似乎工作正常。我得到了正确数量的 IDDescriptionPair 对象的列表。问题是它们都是空白的 - 没有填充任何属性。

这是我使用服务的代码:

Dim client As New HttpClient()
Dim endpoint As New Uri("http://bmpscnt410a/services/v1/personservices/offices/5/principals")

Using response As HttpResponseMessage = client.Get(endpoint)
  response.EnsureStatusIsSuccessful()

  Dim idp As List(Of IDDescriptionPair)
  Try
    idp = response.Content.ReadAsDataContract(Of List(Of IDDescriptionPair))()
  Catch ex As Exception
  End Try
End Using

我已经尝试直接使用 DataContractSerializer,但我得到了相同的结果(这是预期的,我猜)。任何想法将不胜感激。

【问题讨论】:

  • 我应该添加 response.Content.ReadAsString 给我我期望的 XML。

标签: wcf rest datacontractserializer


【解决方案1】:

您使用的类型是 XmlSerializer 类型(使用来自 System.Xml.Serialization 命名空间的属性进行注释,例如 &lt;XmlType()&gt;&lt;XmlRoot()&gt; 等)。为此,您需要使用 XmlSerializer 对其进行反序列化。如果您包含(导入)命名空间System.Xml.Serialization,您应该获得扩展方法ReadAsXmlSerializable,这是您应该用来反序列化响应的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 2011-12-19
    • 1970-01-01
    • 2016-12-28
    • 2011-02-26
    相关资源
    最近更新 更多