Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 block of code where Response.Redirect() was in it worked normally..

Just want to know if this is a known issue or something...

like image 325
Vitor Reis Avatar asked Jun 30 '09 13:06

Vitor Reis


2 Answers

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.

like image 180
M4N Avatar answered Sep 28 '22 07:09

M4N


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
}
like image 28
Philippe Leybaert Avatar answered Sep 28 '22 06:09

Philippe Leybaert