HttpContext抛出HttpException
我写了一个自定义的http处理程序。 我通过编写实现IHttphandler的类来完成此操作。
在那个class级里面我有这样的代码,
context.Response.Clear(); context.Response.ClearHeaders(); context.Response.AddHeader("Content-Disposition", "attachment;filename=" + attachmentFileName); context.Response.AddHeader("Content-Length", new FileInfo(downloadFile).Length.ToString()); context.Response.ContentType = GetMimeType(attachmentFileName); context.Response.TransmitFile(downloadFile); context.Response.Flush(); context.Response.Close();
偶尔我会收到这样的错误,
Exception HttpException The remote host closed the connection The error code is 0x800703E3
或这个,
Exception HttpException The remote host closed the connection The error code is 0x80070040
在这两种情况下,堆栈跟踪都是这样的,
at System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect) at System.Web.Hosting.IIS7WorkerRequest.ExplicitFlush() at System.Web.HttpResponse.Flush(Boolean finalFlush) at System.Web.HttpResponse.Flush()
这在生产中发生,如果我回顾过去几天错误发生了23次,总共上述代码被称为497次。
我怀疑这个失败与用户点击链接不止一次启动上述代码(这会给他们多个下载对话框)有关,然后他们取消其中的一些。 话虽如此,如果它是这样的,我会期望连接在两端优雅地关闭。
如何certificate此错误的确切原因? 我试图启用这样的.NET跟踪为什么不跟踪侦听器记录自定义处理程序流量? 但无法让它发挥作用。
我发现虽然我已启用IIS跟踪来记录失败的请求。 失败再次发生,并且该日志中没有任何内容。
我可以启用任何其他跟踪吗?
我接下来要做的就是这个,
if (context.Response.IsClientConnected) { context.Response.Flush(); context.Response.Close(); } else { LogMessage("Client has disconnected before flush was called", Severity.Information); }
但这没有任何区别。 我猜的原因是客户端在下载过程中断开连接,而不是在调用flush之前。
取出Flush()
和Close()
调用。 你真的不需要它们。 处理程序完成后,它将退出,ASP.NET将处理关闭请求。
此外,当您将内容流式传输到客户端时(在块中将部分添加到响应流中Flush()
应使用Flush()
)。 您不需要将它与TransmitFile()
一起使用。
我遇到了类似的问题,得到了这篇文章解释说应该避免使用Response.End(),而是建议使用CompleteRequest()方法。 MSDN文档也已使用此信息进行了更新。 我希望这可以帮助别人。
使用Response.End()
而不是Response.Flush()
这就是Response.End()
的源代码:
public void End() { if (this._context.IsInCancellablePeriod) { InternalSecurityPermissions.ControlThread.Assert(); Thread.CurrentThread.Abort(new HttpApplication.CancelModuleException(false)); } else if (!this._flushing) { this.Flush(); this._ended = true; if (this._context.ApplicationInstance != null) { this._context.ApplicationInstance.CompleteRequest(); } } }
您使用的.NET框架是什么? 这里的论坛post描述了一个类似的问题,使用IIS7和.NET2.0专门用于客户端断开连接,这是.NET Framework 3.5中解决的一个问题。
实际的错误代码映射到
0x800703E3 "The I/O operation has been aborted because of either a thread exit or an application request."
尝试将Web配置中的max size文件设置为更大的文件。
你可以设置maxRequestLength(以kb为单位)
尽量不要在iis上重新应用app池。
有关此例外的更多详细信息,请访问http://support.microsoft.com/kb/977453
我有时会遇到错误:
Exception message: An error occurred while communicating with the remote host. The error code is 0x80070057.
在生产中是随机的。 它不会在开发或QA中重现。
我将应用此解决方案: Response.IsClientConnected我希望它将修复错误。
资源: