Accepted way to prevent “The remote host closed the connection” exception

后端 未结 3 1304
一个人的身影
一个人的身影 2020-12-20 15:25

I\'m constantly getting the following exception which is caused by a user initiating a download and it consequently failing (or being cancelled):

相关标签:
3条回答
  • 2020-12-20 15:33

    The error occurs when you try to send a response to the client but they have disconnected. You can verify this by setting a breakpoint on the Response.Redirect or wherever you are sending data to the client, wait for Visual Studio to hit the breakpoint, then cancel the request in IE (using the x in the location bar). This should cause the error to occur.

    To capture the error you can use the following:

    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;
        }
    }
    

    Or in C# 6 you can use Exception filters to prevent having to re throw the error:

    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.
    }
    

    Which is a better debugging experience since it will stop on the statement throwing the exception with the current state and all local variables preserved instead of on the throw inside the catch block.

    0 讨论(0)
  • 2020-12-20 15:44

    From a practical perspective, there is nothing wrong with cancelling a download by virtue of a dead computer or a killed web session, therefore catching remote host closed exceptions is perfectly acceptable.

    0 讨论(0)
  • 2020-12-20 15:50

    You cannot prevent a remote Host to close anything.

    And in some protocols this is the normal (or at least accepted) way to say goodbye.

    So you will have to handle this specific exception.

    0 讨论(0)
提交回复
热议问题