"远程主机关闭连接" HttpResponse.Write的错误

时间:2016-11-15 17:33:46

标签: .net httpresponse

我继承了一个旧网站,该网站具有下载用户记录的Excel文档的功能。以下代码导致"远程主机关闭连接。错误代码是0x800704CD。 "错误:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace MySite.ApplicationServices
{
public class OutputFileWriter : IDisposable
{
    private HttpResponse _response;
    private bool _isResponsePrepared;

    public OutputFileWriter(HttpResponse response)
    {
        this._response = response;
    }

    public OutputFileWriter(HttpResponse response, string outputFileName)
        : this(response)
    {
        this.OutputFileName = outputFileName;
    }

    public string OutputFileName { get; set; }

    public virtual void WriteLine(string line)
    {
        if (this._response == null)
            throw new ObjectDisposedException("OutputFileWriter");

        if (!this._isResponsePrepared)
        {
            this.PrepareResponse();
            this._isResponsePrepared = true;
        }

        this._response.Write(line);
    }

    public virtual void Dispose()
    {
        if (this._response != null)
        {
            this._response.Flush();
            this._response.Close();
            this._response = null;
        }
    }

    protected virtual void PrepareResponse()
    {
        if (string.IsNullOrEmpty(this.OutputFileName))
            throw new InvalidOperationException("An output file name is required.");

        this._response.Clear();
        this._response.ContentType = "application/octet-stream";
        this._response.Buffer = this._response.BufferOutput = false;
        this._response.AppendHeader("Cache-Control", "no-store, no-cache");
        this._response.AppendHeader("Expires", "-1");
        this._response.AppendHeader("Content-disposition", "attachment; filename=" + this.OutputFileName);
    }
}
} 

以下是调用它的代码示例(点击'下载'按钮):

 using (OutputFileWriter writer = new OutputFileWriter(this.Response, "users.xls"))
            {
                foreach (string result in searchResults)
                {
                    writer.WriteLine(result);
                }
            }

即使只下载了几个字节,也会发生错误。我知道如果客户取消下载,在正常情况下会发生错误,但是当人们也没有取消时,就会发生错误。我认为这种联系正在消失,但我不确定为什么。

如果它是相关的,则在IIS 7中使用.NET 2.0下的集成应用程序池配置该站点。它也是负载平衡的。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

经过进一步调查后,该文件似乎实际上只能在Firefox中下载。

以下帖子建议从_response.Close()更改为_response.End()可能会有效https://productforums.google.com/forum/#!topic/chrome/8Aykgxa8kWU

然而,我看到了这个HttpResponse.End vs HttpResponse.Close vs HttpResponse.SuppressContent

所以我现在在HttpApplication实例上调用CompleteRequest()。像这样:

旧方法

public virtual void Dispose()
{
    if (this._response != null)
    {
        this._response.Flush();
        this._response.Close();
        this._response = null;
    }
}

新方法:

public virtual void Dispose()
{
    if (this._response != null)
    {
        this._response.Flush();
        this._application.CompleteRequest();
        this._response = null;
    }
}

现在工作正常。