Response.Flush()抛出System.Web.HttpException

我有一个HttpHandler,我用它来处理客户端网站上的某些图像。 当我将图像流输出到响应对象并偶尔调用Flush时会抛出错误。 这是一个代码块

var image = Image.FromStream(memStream); if (size > -1) image = ImageResize.ResizeImage(image, size, size, false); if (height > -1) image = ImageResize.Crop(image, size, height, ImageResize.AnchorPosition.Center); context.Response.Clear(); context.Response.ContentType = contentType; context.Response.BufferOutput = true; image.Save(context.Response.OutputStream, ImageFormat.Jpeg); context.Response.Flush(); context.Response.End(); 

从我读过的,这个exception是由于客户端在进程完成之前断开连接而没有任何要刷新的。

这是我的错误页面的输出

 System.Web.HttpException: An error occurred while communicating with the remote host. The error code is 0x80070057. Generated: Mon, 12 Oct 2009 03:18:24 GMT System.Web.HttpException: An error occurred while communicating with the remote host. The error code is 0x80070057. at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[] status, Byte[] header, Int32 keepConnected, Int32 totalBodySize, Int32 numBodyFragments, IntPtr[] bodyFragments, Int32[] bodyFragmentLengths, Int32 doneWithSession, Int32 finalStatus, Boolean& async) at System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean isFinal) at System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean finalFlush) at System.Web.HttpResponse.Flush(Boolean finalFlush) at System.Web.HttpResponse.Flush() at PineBluff.Core.ImageHandler.ProcessRequest(HttpContext context) in c:\TeamCity\buildAgent\work\79b3c57a060ff42d\src\PineBluff.Core\ImageHandler.cs:line 75 at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) 

context.Response.Flush属于第75行。

有没有办法在执行刷新之前检查这个,而不将它包装在try / catch块中。

虽然我同意Mitchel的意思 – 当你要调用End时,几乎不需要调用flush,如果你在其他地方使用它,你可以先尝试调用Response.IsClientConnnected

获取一个值,该值指示客户端是否仍连接到服务器。

个人在你的实现中,因为下一行是Response.End(),只需删除对Response.Flush()的调用,因为Response.End()会为你处理所有事情。

我意识到这是一个老post,但是当我在寻找类似问题的答案时,它就出现了。 以下内容基本上是从这个SO答案逐字逐句。 Is Response.End()提供了更多背景信息, 认为有害吗? 。

替换为: HttpContext.Current.Response.End();

有了这个:

 HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client. HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event. 

对于未来的读者..

我遇到了这种情况,其中Response.End()因客户端断开连接而抛出错误。

与远程主机通信时发生错误。 错误代码是0x80070057

奇怪的是,StatusDescription中的CRLF导致连接关闭。

 Response.StatusDescription = ex.Message; 

无法将值NULL插入列”,table”; 列不允许空值。 INSERT失败。 \ r \ n该声明已被终止

删除它修复了我的问题。

 Response.StatusDescription = ex.Message.Replace("\r\n", " ");