Get the stream data from WEB API response in windows/ console application

旧城冷巷雨未停 提交于 2020-01-25 06:52:12

问题


I need to download the file from WEB API to windows application via stream data.

WEB API :

public HttpResponseMessage download(string fileid){

var response = new HttpResponseMessage ();    
response.statuscode= HttpStatusCode.Ok;
response.Content =new StreamContent(filestream);// I have a filestream here .
return response;

Here content disposition and content type as added after adding the content . In client side I have try the following.

HttpResponseMessage file = httpclinet.GetAsync("url").Result();

Var stream = file.Content.ReadAsStreamAsync().Result();

using (var data = File.create(@"somepath.txt"))
{
    data.seek(0,seekorigin.begin);

    stream.copyto(data);

}

But I didn't get the output. What am getting is Stream details like version object of stream.content ,statuscode . Like that file was written. How can I write the stream data in this file.


回答1:


what I would suggest to you is using the async-await keywords here, you can change your code like this to get the results:

HttpResponseMessage file = await httpclinet.GetAsync("url");
var stream = await file.Content.ReadAsStreamAsync()

Also you need to add the async keyword to your method like this:

public async Task<HttpResponseMessage> download(string fileid)


来源:https://stackoverflow.com/questions/59817135/get-the-stream-data-from-web-api-response-in-windows-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!