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

Ant*_*haw 11 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();

Run Code Online (Sandbox Code Playgroud)

根据我的阅读,这个异常是由于客户端在进程完成之前断开连接并且没有要刷新的.

这是我的错误页面的输出


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)
Run Code Online (Sandbox Code Playgroud)

context.Response.Flush属于第75行.

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

Mit*_*ers 11

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


Zha*_*uid 7

虽然我同意Mitchel的意思 - 当你要打电话给End时,几乎没有必要打电话给你,如果你在其他地方使用它,你可以尝试Response.IsClientConnnected先打电话.

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