【问题标题】:Get the stream data from WEB API response in windows/ console application从 windows/ 控制台应用程序中的 WEB API 响应中获取流数据
【发布时间】:2020-01-20 04:48:40
【问题描述】:

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

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;

此处添加内容后添加的内容配置和内容类型。 在客户端,我尝试了以下操作。

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.contentstatuscode 的版本对象。就像那个文件被写了一样。 如何在这个文件中写入流数据。

【问题讨论】:

    标签: c# asp.net-web-api download stream


    【解决方案1】:

    我建议您在这里使用async-await 关键字,您可以像这样更改代码以获得结果:

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

    您还需要将 async 关键字添加到您的方法中,如下所示:

    public async Task<HttpResponseMessage> download(string fileid)
    

    【讨论】:

    • 我尝试了您所说的。收到了相同的答案。我认为没有太大区别。
    • 我的方法可以吗??
    • @user9949432 你也需要在这里添加:var stream = await file.Content.ReadAsStreamAsync()
    • 是的,我在两个地方都添加了 await,但文件仍然写错了。
    猜你喜欢
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多