When I use Response.Redirect(...) to redirect my form to a new page I get the error:
A first chance exception of type \'System.Threading.ThreadAbortEx
I know I'm late, but I've only ever had this error if my Response.Redirect
is in a Try...Catch
block.
Never put a Response.Redirect into a Try...Catch block. It's bad practice
As an alternative to putting the Response.Redirect into the Try...Catch block, I'd break up the method/function into two steps.
inside the Try...Catch block performs the requested actions and sets a "result" value to indicate success or failure of the actions.
outside of the Try...Catch block does the redirect (or doesn't) depending on what the "result" value is.
This code is far from perfect and probably should not be copied since I haven't tested it.
public void btnLogin_Click(UserLoginViewModel model)
{
bool ValidLogin = false; // this is our "result value"
try
{
using (Context Db = new Context)
{
User User = new User();
if (String.IsNullOrEmpty(model.EmailAddress))
ValidLogin = false; // no email address was entered
else
User = Db.FirstOrDefault(x => x.EmailAddress == model.EmailAddress);
if (User != null && User.PasswordHash == Hashing.CreateHash(model.Password))
ValidLogin = true; // login succeeded
}
}
catch (Exception ex)
{
throw ex; // something went wrong so throw an error
}
if (ValidLogin)
{
GenerateCookie(User);
Response.Redirect("~/Members/Default.aspx");
}
else
{
// do something to indicate that the login failed.
}
}
Also I tried other solution, but some of the code executed after redirect.
public static void ResponseRedirect(HttpResponse iResponse, string iUrl)
{
ResponseRedirect(iResponse, iUrl, HttpContext.Current);
}
public static void ResponseRedirect(HttpResponse iResponse, string iUrl, HttpContext iContext)
{
iResponse.Redirect(iUrl, false);
iContext.ApplicationInstance.CompleteRequest();
iResponse.BufferOutput = true;
iResponse.Flush();
iResponse.Close();
}
So if need to prevent code execution after redirect
try
{
//other code
Response.Redirect("")
// code not to be executed
}
catch(ThreadAbortException){}//do there id nothing here
catch(Exception ex)
{
//Logging
}
Here's the official line on the problem (I couldn't find the latest, but I don't think the situation has changed for later versions of .net)
This is just how Response.Redirect(url, true)
works. It throws the ThreadAbortException
to abort the thread. Just ignore that exception. (I presume it is some global error handler/logger where you see it?)
An interesting related discussion Is Response.End() Considered Harmful?.
I had that problem too.
Try using Server.Transfer
instead of Response.Redirect
Worked for me.
What I do is catch this exception, together with another possible exceptions. Hope this help someone.
catch (ThreadAbortException ex1)
{
writeToLog(ex1.Message);
}
catch(Exception ex)
{
writeToLog(ex.Message);
}