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

时间:2009-10-12 18:16:28

标签: c# asp.net image httphandler

我有一个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();

从我读过的内容来看,这个异常是由于客户端在进程完成之前断开连接并且没有要刷新的。

以下是我的错误页面的输出


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块中。?

4 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:7)

虽然我同意Mitchel - 因为您要打电话给End,因此无需拨打同花,如果您在其他地方使用此处,则可以先尝试拨打Response.IsClientConnnected

  

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

答案 2 :(得分:0)

我意识到这是一个老帖子,但是当我在寻找类似问题的答案时,它就出现了。以下内容基本上是this SO answer的逐字逐句。更多背景信息可在Is Response.End() considered harmful?获得。

替换为: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.

答案 3 :(得分:0)

对于未来的读者..

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

  

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

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

Response.StatusDescription = ex.Message;
  

无法将值NULL插入列'',table'';   列不允许空值。 INSERT失败。 \ r \ n 声明已经出现   终止

删除它解决了我的问题。

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