我正在构建一个可以返回XML和Json的WCF休息服务。它可以工作但是当我调用返回XML时,我的XML是一个字符串而不是XML。我认为这是因为我正在将数据表转换为XML。
WCF以适当的XML提供响应,因此我不确定如何将数据XML /文本放在WCF XML响应中并使其成为实际的XML。
这是我的代码......如果需要,我可以提供更多代码.. 我相信我会这样做是正确的,但我错过了一些东西。 任何帮助将不胜感激。
IRest.vb
<OperationContract()>
<WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Xml,
BodyStyle:=WebMessageBodyStyle.Bare,
UriTemplate:="xml/getassetnames/?key={key}")>
Function GetAssetNamesXML(key As String) As String
将数据表转换为XML的函数
Public Shared Function ToXml(dt As DataTable) As String
Using textWriter = New StringWriter()
Dim settings = New XmlWriterSettings()
settings.Indent = True
settings.IndentChars = " "
settings.OmitXmlDeclaration = True
Using xmlWriter__1 = XmlWriter.Create(textWriter, settings)
dt.WriteXml(xmlWriter__1)
Return textWriter.ToString()
End Using
End Using
End Function
实现GetAssetNames IRest .. my .svc
Public Function GetAssetNamesXML(ByVal Key As String) As String Implements IAquaViewRest.GetAssetNamesXML
Dim dt As New DataTable
dt = GetAssetNamesDT(Key) 'runs a function that goes to the database and returns a DT
Return ToXml(dt)
dt.Clear()
End Function
答案 0 :(得分:0)
我没有得到任何回复,但想发布我的解决方案,以便其他人可以使用它。
主要问题是在操作协定中使用字符串作为函数并将DT转换为XML,然后将响应设置为XML,将其序列化。不确定我是否使用了正确的术语,但基本上它用一个字符串标签封装你的DT就是这样。
所以解决这个问题的方法是将您的操作合同作为System.IO.Stream。这也意味着您需要更好的转换DT到XML函数..
这是最终的代码......
<OperationContract()>
<WebInvoke(Method:="GET", BodyStyle:=WebMessageBodyStyle.Wrapped, ResponseFormat:=WebMessageFormat.Xml,
UriTemplate:="xml/getassetnames/?key={key}")>
Function GetAssetNamesXML(key As String) As System.IO.Stream
DT to XML
Public Shared Function ToXml(dt As DataTable) As String
Dim settings = New XmlWriterSettings()
settings.Indent = True
settings.Encoding = Encoding.GetEncoding("utf-8")
settings.IndentChars = " "
Dim memStream As New MemoryStream()
Dim writer As XmlWriter = XmlWriter.Create(memStream, settings)
Using xmlWriter__1 = XmlWriter.Create(memStream, settings)
dt.WriteXml(xmlWriter__1)
Dim xml As String = Encoding.GetEncoding("utf-8").GetString(memStream.ToArray())
Return xml
End Using
End Function
svc.vb
Public Function GetAssetNamesXML(ByVal Key As String) As System.IO.Stream Implements IAquaViewRest.GetAssetNamesXML
Dim dt As New DataTable
dt = GetAssetNamesDT(Key)
Dim TempStr As String = ToXml(dt)
Dim resultBytes As Byte() = Encoding.UTF8.GetBytes(TempStr)
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"
Return New MemoryStream(resultBytes)
dt.Clear()
End Function