Thursday, June 22, 2006

Response.Redirect

As a ASP coder I used a lot of Response.Redirect(webiste) statements while scripting and that was good...but now..when jumping to ASP.net and C# I had a few problems while using Response.Redirect("website")...and that is because I was placing the redirect statements into try-catch blocks and the Response.Redirect("website") statement throws an exception ThreadAbortException so if you try something like this:

try
{
///code that might throw exceptions
Response.Redirect("default.aspx");
}
catch(ThreadAbortException ex)
{
Response.Redirect("error.aspx")
}


you would always get the user to the error.aspx page instead of the default.aspx. The same thing happens if you try to use Response.Redirect("Default.aspx",true).

This happens because the Response.Redirect method calls the Response.End method that thrown this ThreadAbortException. There are several ways to avoid this problems:
1.
string url = String.Empty;
try
{
///code that might throw exceptions
url="default.aspx";
}
catch(ThreadAbortException ex)
{
url="error.aspx";
}
Response.Redirect(url);


This will redirect the user to the default.aspx page because the ThreadAbortException is not thrown by the Response.End method anymore.
2.
try
{
///code that might throw exceptions
Response.Redirect("default.aspx",false);
}
catch(ThreadAbortException ex)
{
Response.Redirect("error.aspx")
}

This will work fine(getting the user to the default.aspx page) because the false parameter in the Response.Redirect means that the Response.Redirect meghod will not call the Response.End method...but this could cause other damage so usually if you use this method put a return; statement after the redirect. Like this:
try{
///code that might throw exceptions
Response.Redirect("default.aspx",false);
return;
}
catch(ThreadAbortException ex)
{
Response.Redirect("error.aspx")
}



3. You can use Server.Transfer instead of Response.Redirect though this has its drawbacks too. First of all Server.Transfer transfers the user to another page on the server side so the user does not see the actual URL of the page that he is working on so getting the page in the favourites folder is not an option.

2 comments:

Anonymous said...

Cding your Response.Redirect() outside of the try/catch does not prevent it from throwing a ThreadAbortException. The easiest way to manage this situation is this.

catch (ThreadAbortException) {}

Anonymous said...

http://dotnetguts.blogspot.com/2006/11/responseredirecturltrue-vs.html