简体   繁体   中英

ASP.NET Response.Redirect() issue not working at false parameter

Have trouble with the Response.Redirect() and getting the error:

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

I've googled and found some topics here, like: Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Where people are offering to set the 2nd argument to the false value to make it work, like:

Response.Redirect("PageName.aspx", false);

But as for my program it isn't redirecting to the new one... It just continues to stay at this page.

I've done a breakpoint on other page, which to I want to redirect. But there wasn't any event for the breakpoint to catch. Looks like it just doesn't send the request to another page.

My code is rather big, so I've posted the code not here, but at ideone: http://ideone.com/bQzCJd

The Redirect() method is on the 57th line , which:

  • occurs an exception, if the 2nd argument is set to true
  • nothing happen, if is set to false

What must I do to fix it?

occurs an exception, if the 2nd argument is set to true

Yes, a ThreadAbortException because you redirect in a Try-Catch .

Why don't you use Response.Redirect("PageName.aspx") but after the try/catch ? Use a bool variable eg redirectCabinet which you can check before your redirect:

bool redirectCabinet = false;
try
{
    // ...
    if (tmpStr != String.Empty)
    {
        if (pageHandler.Request.HttpMethod == "GET")
        {
            if (pageHandler.Request.Params["method"] == "checkAuth")
            {
                // ...
                bool userExists = Convert.ToBoolean(mysqlObject.MakeScalar(ref mysqlConn,
                if (userExists)
                {
                   // ...
                    redirectCabinet = true;
                    //Response.Redirect("Cabinet.aspx");
                }
                // ...
            }
        }
        //....
    }
} catch (Exception exc)
{
    exc.ToString();
}

if(redirectCabinet)
    Response.Redirect("Cabinet.aspx");

I suggest you to avoid the Abort Exception, and use the true to end the execution and move to the next page.

try
{
    // this is throw the ThreadAbortException exception
    Response.Redirect("SecondEndPage.aspx", true);
}
catch (ThreadAbortException)
{
    // ignore it because we know that come from the redirect
}
catch (Exception x)
{

}

Similar : https://stackoverflow.com/a/14641145/159270

Even with the solutions presented in the comments, it is not working as it should but if redirected with true endRequest , it should work.

Like this:

if(redirectCabinet)
    Response.Redirect("Cabinet.aspx",true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM