如何将Stream转换为对象 [英] How to convert a Stream into an object

查看:192
本文介绍了如何将Stream转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将流转换为对象.

我有一个WebApi

I have a 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方法称为波纹管:

Now I'm calling this GET method as bellow:

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

好吧,我的呼叫成功了,但是一旦我将所有数据输入流中,如何再次将它们作为相同的 AttachmentViewModel 对象进行检索.并且如果API返回任何错误,如何读取它.

Well, my call is successful but once I get all data into my stream how can I again retrieve them all as the same AttachmentViewModel object. And if the API returns any error how to read it.

推荐答案

您可以使用

You can use the DownloadString method from WebClient and deserialize it into your model (by using JSON.NET for example).

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

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

If an error occurs, a corresponding WebException will be thrown.

这篇关于如何将Stream转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆