异步读取HttpClient流

时间:2014-07-29 07:29:59

标签: c# asynchronous

我在下面写了async方法从 WebApi 下载文件流。但在等待networkStrm = await httpClient.GetStreamAsync(_downloadRestUrl);

的结果时
  

无法从传输连接中读取数据:现有数据   连接被远程主机强行关闭。潜在的   连接已关闭:接收时发生意外错误。

    async internal Task<Stream> DownloadAsync(string _downloadRestUrl)
    {
        Stream networkStrm = null;
        try
        {
            var baseUrl = GetBaseUrl(_downloadRestUrl);

            HttpClient httpClient = new HttpClient();
            httpClient.Timeout = TimeSpan.FromMinutes(5);
            httpClient.BaseAddress = baseUrl;
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));

            networkStrm = await httpClient.GetStreamAsync(_downloadRestUrl);
            networkStrm.Seek(0, SeekOrigin.Begin);
        }
        catch (Exception ex)
        {

        }
        return networkStrm;
    }

0 个答案:

没有答案