【发布时间】:2016-11-15 17:33:45
【问题描述】:
我继承了一个旧网站,该网站具有下载用户记录的 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 下的集成应用程序池。它也是负载平衡的。
有什么想法吗?
【问题讨论】:
-
可能想读一读this answer on Proper use of the IDisposable interface。我并不是说你做错了,但在处理
IDisposable时仔细检查总是一个好主意。 -
@MikeMcCaughan 奇怪的是,它似乎在 Visual Studio 中本地运行良好。可能指向 IIS 或应用程序池设置。
标签: .net httpresponse