如何将Stream转换为对象

时间:2015-01-23 09:18:26

标签: c# asp.net-web-api

如何将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返回任何错误,如何阅读它。

1 个答案:

答案 0 :(得分:3)

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

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

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