Response.Redirect and thread was being aborted err

2020-02-09 03:53发布

问题:

I had this error Thread was being aborted., this afternoon in my error log.

The code that caused this error is:

Response.Redirect("Login.aspx", true);

If I change the bool value to false, the error log becomes empty and this error stops coming again, but the program stops working.

If I keep it as such, I am getting this error like nuisance.

I want to know the alternative for using Response.Redirect passing true as the value for the endResponse parameter.

回答1:

I catch this exception and swallow it because ASP.NET is using exceptions for flow control rather than for an exceptional circumstance.

try
{
    // Do stuff.
}
catch(ThreadAbortException)
{
    // Do nothing. ASP.NET is redirecting.
    // Always comment this so other developers know why the exception 
    // is being swallowed.
}
catch(OtherExceptionTypes ex)
{
    // Log other types of exception.
}


回答2:

As stated in Response.Redirect(url) ThreadAbortException Solution:

The ThreadAbortException is thrown when you make a call to Response.Redirect(url) because the system aborts processing of the current web page thread after it sends the redirect to the response stream. Response.Redirect(url) actually makes a call to Response.End() internally, and it's Response.End() that calls Thread.Abort() which bubbles up the stack to end the thread. Under rare circumstances the call to Response.End() actually doesn't call Thread.Abort(), but instead calls HttpApplication.CompleteRequest().

Or simply move Response.Redirect("~/Membership/UserRegistration.aspx"); out of the Try/Catch block.



回答3:

you can change like this Response.Redirect ("Login.aspx",false) then it wont abort.



回答4:

For all caught errors where you want to redirect, create a 'GoTo' destined out of the Try Catch as follows:

    Try 

       'do stuff

    Catch ex As Exception

        'logging
        GoTo MyRedirection

    End Try

    'Prevent redirection in case of no errors
    Exit Sub

MyRedirection:
    Response.Redirect("login.aspx", True)

This neither causes thread abortion nor requires multiple catches.