Is there something that prevents Response.Redirect to work inside try-catch block?

前端 未结 5 1212
旧时难觅i
旧时难觅i 2020-12-10 06:05

I got some weird error with response.redirect() and the project wasn\'t building at all.. when I removed the try-catch block that was surrounding the b

相关标签:
5条回答
  • 2020-12-10 06:35

    As Martin points out, Response.Redirect throws a ThreadAbortException. The solution is to re-throw the exception:

    try  
    {
       Response.Redirect(...);
    }
    catch(ThreadAbortException)
    {
       throw; // EDIT: apparently this is not required :-)
    }
    catch(Exception e)
    {
      // Catch other exceptions
    }
    
    0 讨论(0)
  • 2020-12-10 06:38

    Martin is correct, a ThreadAbortException gets thrown when you use a Response.Redirect, see the kb article here

    0 讨论(0)
  • 2020-12-10 06:49

    If I remember correctly, Response.Redirect() throws an exception to abort the current request (ThreadAbortedException or something like that). So you might be catching that exception.

    Edit:

    This KB article describes this behavior (also for the Request.End() and Server.Transfer() methods).

    For Response.Redirect() there exists an overload:

    Response.Redirect(String url, bool endResponse)
    

    If you pass endResponse=false, then the exception is not thrown (but the runtime will continue processing the current request).

    If endResponse=true (or if the other overload is used), the exception is thrown and the current request will immediately be terminated.

    0 讨论(0)
  • 2020-12-10 07:00

    You may have referenced a variable that is declared inside the try block.

    For example, the below code is invalid:

    try
    {
      var b = bool.Parse("Yeah!");
    }
    catch (Exception ex)
    {
      if (b)
      {
        Response.Redirect("somewhere else");
      }
    }
    

    You should move out the b declaration to outside the try-catch block.

    var b = false;
    try
    {
      b = bool.Parse("Yeah!");
    }
    catch (Exception ex)
    {
      if (b)
      {
        Response.Redirect("somewhere else");
      }
    }
    
    0 讨论(0)
  • 2020-12-10 07:02

    I don't think there is any known issue here.

    You simply can't do a Redirect() inside a try/catch block because Redirect leaves the current control to another .aspx (for instance), which leaves the catch in the air (can't come back to it).

    EDIT: On the other hand, I might have had all of this figured backwards. Sorry.

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