簡體   English   中英

如何將Stream轉換為對象

[英]How to convert a Stream into an 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<AttachmentViewModel>(data);

如果發生錯誤,將拋出相應的WebException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM