我经常收到以下异常,这是由用户启动下载并因此失败(或被取消)引起的:
Error Message : The remote host closed the connection. The error code is 0x80072746. Stack Trace : 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
我在网上找遍了,and found an interesting article ,但是似乎没有明确的答案作为防止这种情况填满日志的最佳方法。
用户没有看到任何错误,应用程序中也没有实际问题,因为它仅在(据我了解)无法控制的情况下(用户取消下载或失去连接)发生,但必须有一种方法来防止这种情况发生正在报告异常。
我不想这么说,但我很想检查这个异常并空捕获阻止它的屁股 - 但这让我觉得自己像个肮脏的程序员。
那么 - 防止此异常填满我的邮箱的公认方法是什么?
最佳答案
当您尝试向客户端发送响应但他们已断开连接时,就会发生错误。您可以通过在 Response.Redirect 或任何您向客户端发送数据的地方设置断点来验证这一点,等待 Visual Studio 命中断点,然后在 IE 中取消请求(使用地址栏中的 x)。这应该会导致错误发生。
要捕获错误,您可以使用以下命令:
try
{
Response.Redirect("~/SomePage.aspx");
Response.End();
}
catch (System.Threading.ThreadAbortException)
{
// Do nothing. This will happen normally after the redirect.
}
catch (System.Web.HttpException ex)
{
if (ex.ErrorCode == unchecked((int)0x80070057)) //Error Code = -2147024809
{
// Do nothing. This will happen if browser closes connection.
}
else
{
throw ex;
}
}
或者在 C# 6 中,您可以使用异常过滤器来防止必须重新抛出错误:
try
{
Response.Redirect("~/SomePage.aspx");
Response.End();
}
catch (System.Threading.ThreadAbortException)
{
// Do nothing. This will happen normally after the redirect.
}
catch (System.Web.HttpException ex) when (ex.ErrorCode == unchecked((int)0x80070057))
{
// Do nothing. This will happen if browser closes connection.
}
这是更好的调试体验,因为它会在抛出异常并保留当前状态和所有局部变量的语句处停止,而不是在 catch block 内的 throw 处停止。
关于c# - 防止 "The remote host closed the connection"异常的可接受方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5679163/