C# 文件下载HTTPHandler在HttpResponse.Flush上引发错误
我有一个HTTPHandler,它向客户端发送一个文件。我只看到有时会记录错误。所有情况下下载的文件都非常小,小于1MB。以下是错误/堆栈跟踪: 远程主机关闭了连接。 错误代码为0x800703E3 在System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationErrorInt32结果中,布尔值为0 位于System.Web.Hosting.IIS7WorkerRequest.ExplicitFlush 位于System.Web.HttpResponse.FlushBoolean finalFlush 代码如下:C# 文件下载HTTPHandler在HttpResponse.Flush上引发错误,c#,asp.net,httphandler,C#,Asp.net,Httphandler,我有一个HTTPHandler,它向客户端发送一个文件。我只看到有时会记录错误。所有情况下下载的文件都非常小,小于1MB。以下是错误/堆栈跟踪: 远程主机关闭了连接。 错误代码为0x800703E3 在System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationErrorInt32结果中,布尔值为0 位于System.Web.Hosting.IIS7WorkerRequest.ExplicitFlush 位于System.Web.HttpResp
public class DownloadHttpHandler : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
//Checking permission, getting the file path, etc...
ResponseUtil.SendDownloadFile(context.Response, fullPath);
}
}
public static class ResponseUtil
{
/// <summary>Sends the specified file.</summary>
public static void SendDownloadFile(HttpResponse response, string path, string contentType)
{
FileInfo fileInfo = new FileInfo(path);
BeginSendDownloadFile(response, fileInfo.Name, contentType, fileInfo.Length);
using (FileStream stream = File.OpenRead(path))
{
stream.CopyTo(response.OutputStream);
}
EndSendDownloadFile(response);
}
/// <summary>Prepares the output stream to send a downloadable file.</summary>
public static void BeginSendDownloadFile(HttpResponse response, string filename, string contentType, long contentLength)
{
if (response.IsClientConnected)
{
response.AddHeader("Content-Disposition", "attachment; filename={0}".FormatString(filename));
response.ContentType = contentType;
response.AddHeader("Content-Length", contentLength.ToString());
}
}
/// <summary>Flushes and closes the output stream.</summary>
public static void EndSendDownloadFile(HttpResponse response)
{
if (response.IsClientConnected)
{
response.Flush();
response.Close();
}
}
}
我想下载可能被取消了,所以我添加了响应。iClient在几个位置进行了连接检查。但我仍然看到了错误
我应该不调用Flush和Close吗?尝试在所有逻辑的开头设置Response.Buffer=True。默认情况下,缓冲是打开的。设置它可能会产生更大的效果,因为它会将内容直接发送到客户端。我不认为你需要结束回复。asp.net将为您解决此问题。此外,关闭缓冲将消除刷新的需要。客户端浏览器可能知道内容长度,一旦收到这么多字节,它将在服务器上进行刷新和关闭之前关闭连接?