在Windows /控制台应用程序中从WEB API响应获取流数据 [英] Get the stream data from WEB API response in windows/ console application

查看:81
本文介绍了在Windows /控制台应用程序中从WEB API响应获取流数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过流数据将文件从WEB API下载到Windows应用程序。

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);

}

但是我没有得到输出。得到的是
流详细信息,例如 stream.content statuscode 的版本对象。就像写了那个文件一样。
如何在该文件中写入流数据。

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.

推荐答案

我建议您使用的<在此处使用href = https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/ rel = nofollow noreferrer> async-await 关键字,您可以像这样更改代码以获取结果:

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()

此外,您还需要添加 async 关键字,例如:

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

public async Task<HttpResponseMessage> download(string fileid)

这篇关于在Windows /控制台应用程序中从WEB API响应获取流数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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