如何将Stream转换为对象

如何将Stream转换为Object。

我有一个WebApi

[HttpGet] public AttachmentViewModel DownloadAttachementDetailsByIds(int attachementDetaisId) { AttachmentViewModel attachment = new AttachmentViewModel { AttachmentName = "Observe", AttachmentType = ".c", AttachmentDetailsID = 123, AttachmentDetails = Encoding.ASCII.GetBytes("some contant"), AttachmentSize = 12 //some valid size }; return attachment; } 

现在我把这个GET方法调用如下:

  WebClient webClient = new WebClient(); Stream stream = webClient.OpenRead(documentRepositoryApiUrl + "DocRepoApi/DownloadAttachementDetailsById?attachementDetaisId=97"); 

好吧,我的调用成功但是一旦我将所有数据都输入到我的流中,我怎样才能再次将它们全部检索为相同的AttachmentViewModel对象。 如果API返回任何错误如何阅读它。

您可以使用WebClientDownloadString方法并将其反序列化到您的模型中(例如,使用JSON.NET)。

 WebClient webClient = new WebClient(); var data = webClient.DownloadString(url); var deserialized = JsonConvert.DeserializeObject(data); 

如果发生错误,将抛出相应的WebException