来自response.Content.ReadAsStreamAsync()的流不是随机可读的 [英] Stream from response.Content.ReadAsStreamAsync() is not readable randomly

查看:972
本文介绍了来自response.Content.ReadAsStreamAsync()的流不是随机可读的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个.Net Web API应用程序,其中以下代码正在调用我的其他c#应用程序以下载文件,然后将其保存在磁盘上.有时一切正常,我得到了文件,但有时下面的代码无法读取流,并且在其他应用程序中可以看到远程连接关闭异常.

I am making a .Net Web API application in which the following code is making call to my different c# application to download file and then save it on the disk. Sometimes everything works fine and I get the file but sometimes the below code is not able to read the stream and I can see the remote connection closed exception in my other application.

public async Task<string> GetFilePathAsync(TestModel model)
{
    string filePath = string.Empty;
    var response = await cgRequestHelper.DownloadAsync(model);  

    if (response.IsSuccessStatusCode)
    {                    
        filePath = await SaveCgStreamAsync(cgResponse, serviceModel.FileName);
    }
    return filePath;
}

public async Task<HttpResponseMessage> DownloadAsync(TestModel model)
{            
    if (model == null)
        throw new ArgumentNullException("model");
    if (string.IsNullOrEmpty(model.Url))
        throw new ArgumentNullException("Url");
    if (model.Headers == null)
        throw new ArgumentNullException("Headers");

    HttpResponseMessage response;
    using (HttpClient httpClient = new HttpClient())
    {
        foreach (var header in model.Headers)
        {
            httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
        }
        response = await httpClient.GetAsync(model.Url, HttpCompletionOption.ResponseHeadersRead); 
    }
    return response;            
}        

public async Task<string> SaveCgStreamAsync(HttpResponseMessage response, string fileName)
{
    if (response == null)
        throw new ArgumentNullException("response");
    if (string.IsNullOrEmpty(fileName))
        throw new ArgumentNullException("fileName");

    var filePath = _CreateTemporaryLocation(fileName);
    Stream cgStream = null;
    Stream fileStream = null;
    try
    {
        cgStream =  await response.Content.ReadAsStreamAsync();
        fileStream = File.Open(filePath, FileMode.Create);
        await cgStream.CopyToAsync(fileStream);
    }
    catch(Exception e)
    {
        throw;
    }
    finally
    {
        if(cgStream != null)
            cgStream.Dispose();
        if(fileStream != null)
            fileStream.Dispose();
    }

    return filePath;            
}

我已经在Global.asax.cs中设置了ServicePointManager.DefaultConnectionLimit = 1000

I have set ServicePointManager.DefaultConnectionLimit = 1000 in Global.asax.cs

在我当前的应用程序中,我遇到了"await cgStream.CopyToAsync(fileStream);"异常.尝试读取cgStream时显示一行.例外是无法访问封闭的流". InnerException为null 另一个应用程序异常是: System.Web.HttpException:远程主机关闭了连接.错误代码为0x800703E3. 在System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32结果,布尔throwOnDisconnect) 在System.Web.Hosting.IIS7WorkerRequest.ExplicitFlush() 在System.Web.HttpResponse.Flush(Boolean finalFlush,布尔异步)

In my current application I am getting exception on "await cgStream.CopyToAsync(fileStream);" line when it tries to read the cgStream. The exception is "Cannot access a closed Stream." with null InnerException The other application exception is: System.Web.HttpException: The remote host closed the connection. The error code is 0x800703E3. at System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect) at System.Web.Hosting.IIS7WorkerRequest.ExplicitFlush() at System.Web.HttpResponse.Flush(Boolean finalFlush, Boolean async)

平均而言,十分之一的请求失败,并出现上述错误.由于它是随机的并且并不总是会失败,因此很难解决问题.

On an average, 1 out of 10 request is failing with the above error. Since it is random and not always failing, it is very difficult to troubleshoot the problem.

上面的代码是在以下人员的帮助下编写的: http://www.tugberkugurlu.com/archive/ficiently-streaming-large-http-responses-with-httpclient

The above code is written with the help from: http://www.tugberkugurlu.com/archive/efficiently-streaming-large-http-responses-with-httpclient

感谢您提供与该问题有关的任何帮助!

Any help related to this problem is appreciated!

谢谢

推荐答案

我在代码中发现了问题: 问题是我正在'using'中初始化HttpClient对象,并在using范围之外使用它的响应.这将处理HttpClient对象,从而断开远程连接,这就是为什么我无法流式传输内容的原因.随机行为是因为我们不知道对象何时会被处置,有时在流传输之前不会被处置,有时会被处置.

I figured out the problem in the code: The problem was that I was initializing HttpClient object in 'using' and using its response outside the using scope. This will dispose the HttpClient object, hence breaking the remote connection and that is why I am not able to stream the content. The random behavior was because we do not know when will the object gets disposed, sometimes it does not gets disposed before streaming and sometimes it does.

这篇关于来自response.Content.ReadAsStreamAsync()的流不是随机可读的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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