Reputation: 2393
How to convert a Stream into an Object.
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;
}
Now I'm calling this GET method as bellow:
WebClient webClient = new WebClient();
Stream stream = webClient.OpenRead(documentRepositoryApiUrl + "DocRepoApi/DownloadAttachementDetailsById?attachementDetaisId=97");
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.
Upvotes: 2
Views: 1454
Reputation: 12324
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);
If an error occurs, a corresponding WebException
will be thrown.
Upvotes: 4