ReadAsDataContract<;字符串[]>;-意外的文件结尾

本文关键字:意外 文件 结尾 lt 字符串 ReadAsDataContract gt | 更新日期: 2023-09-27 18:27:21

我有一个程序,它调用一个rest服务并返回一个字符串数组。当我试图读取字符串数组时,我得到了一个异常意外的文件结尾。如果我让服务返回一个只包含数组的第一个项的字符串,它就会工作。导致此异常的ReadAsDataContract<>()缺少什么?

    var returnElement = response.Content.ReadAsDataContract<string[]>();

异常是XMLException:意外的文件结尾。

堆栈跟踪-

at System.Xml.EncodingStreamWrapper.ReadBOMEncoding(Boolean notOutOfBand)
       at System.Xml.EncodingStreamWrapper..ctor(Stream stream, Encoding encoding)
       at System.Xml.XmlUTF8TextReader.SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
       at System.Runtime.Serialization.XmlObjectSerializer.ReadObject(Stream stream)
       at System.Runtime.Serialization.DataContractContentExtensions.ReadAsDataContract[T](HttpContent content, DataContractSerializer serializer)
       at System.Runtime.Serialization.DataContractContentExtensions.ReadAsDataContract[T](HttpContent content)
       at RestConsumption.Program.GetDevices() in **********'documents'visual studio 2010'Projects'RestPractice'RestConsumption'Program.cs:line 55
       at RestConsumption.Program.Main(String[] args) in *********'documents'visual studio 2010'Projects'RestPractice'RestConsumption'Program.cs:line 26
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

ReadAsDataContract<;字符串[]>;-意外的文件结尾

我用一种非常简单的方式解决了这个问题,但我仍然不明白它为什么有效。我只是做了

    string[] returnElement = response.Content.ReadAsDataContract<string[]>();

而不是

    var returnElement = response.Content.ReadAsDataContract<string[]>();

而且效果很好。如果有人告诉我为什么这样做有效,我会称赞他们回答了这个问题。