ASP.NET Response.Redirect()问题无法在false参数下工作

时间:2013-03-10 00:36:13

标签: asp.net redirect expression response evaluate

Response.Redirect()遇到问题并收到错误:

无法评估表达式,因为代码已优化或本机框架位于调用堆栈之上

我用Google搜索并在此处找到了一些主题,例如: Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

人们提出将第二个参数设置为false值以使其有效,例如:

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

但至于我的程序,它并没有重定向到新的...它只是继续留在这个页面。

我在其他页面上做了一个断点,我要重定向。但是没有任何关于断点的事件。看起来它只是不将请求发送到另一个页面。

我的代码相当大,所以我发布的代码不是在这里,而是在ideone: http://ideone.com/bQzCJd

Redirect()方法位于57th line,其中:

    如果第二个参数设置为true ,则
  • 发生异常
  • 如果设置为false
  • ,则不会发生任何事情

我该怎么做才能解决它?

3 个答案:

答案 0 :(得分:1)

  如果第二个参数设置为true,则

发生异常

是的,ThreadAbortException,因为Try-Catch中的redirect

为什么不在Response.Redirect("PageName.aspx")之后使用try/catch?使用bool变量,例如您可以在重定向之前检查redirectCabinet

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");

答案 1 :(得分:1)

我建议您避免Abort Exception,并使用true结束执行并转到下一页。

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)
{

}

类似:https://stackoverflow.com/a/14641145/159270

答案 2 :(得分:0)

即使使用评论中提供的解决方案,它仍然无法正常工作,但如果重定向为真endRequest,它应该可以正常工作。

像这样:

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