我已經繼承了一箇舊網站,該網站具有下載用戶記錄的Excel文檔的功能。下面的代碼是造成「遠程主機關閉了連接錯誤代碼是0x800704CD。」錯誤:「遠程主機關閉連接」錯誤HttpResponse.Write
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下。它也是負載平衡的。
有什麼想法?
可能想給[這個答案正確使用IDisposable接口](http://stackoverflow.com/a/538238/215552)閱讀。我並不是說你做錯了,但是當你處理'IDisposable'時,仔細檢查一下是個好主意。 –
@MikeMcCaughan奇怪的是,它似乎很好地在Visual Studio中本地運行。也許可能指向IIS或應用程序池設置。 – user806982