Response.Redirect(URL,false) - 重定向后事件管理

jwe*_*kes 6 c# asp.net session response.redirect

可能重复:
Response.Redirect导致System.Threading.ThreadAbortException

ASP/C#.NET(Web表单,而不是MVC)

更新:刚发现一个相关的帖子(可能会重复这个帖子):为什么Response.Redirect导致System.Threading.ThreadAbortException?

~~~

经过一番研究后,我逐渐认识到,一般来说,在使用Response.Redirect()时,最好为第二个参数传递FALSE,以避免System.Threading.ThreadAbortException.(http://blogs.msdn.com/b/tmarq/archive/2009/06/25/correct-use-of-system-web-httpresponse-redirect.aspx)

我的问题是,"是否有一种推荐的方式(模式)用于管理(即跳过)重定向后触发的页面事件中的处理,当为第二个参数传递false时?"

当我在Page_Load()中检查并重定向过期的会话时,这对我来说主要是一个问题.每次重定向然后在每个事件的顶部检查该标志时,可能必须设置"_Rreirected"标志似乎非常繁琐.我过去不必担心这个问题因为我总是为第二个参数传递TRUE,不知道更好.

下面是一些代码,显示了我不想要做的事情(在处理每个事件之前检查_Redirected).也许我正在寻找的是更好的会话到期处理模式.

任何有关如何改进此处理的建议都将不胜感激.

private bool _Redirected = false;    

protected void Page_Load(object sender, EventArgs e)
{
  if (Session["key"] == null)
  {
    Response.Redirect("SessionExpired.aspx", false);
    Context.ApplicationInstance.CompleteRequest();

    _Redirected = true;
  }       
}

protected void Page_PreRender(object sender, EventArgs e)
{
  if (!_Redirected)
  {
    // do Page_PreRender() stuff...
  }
}

protected void Button1_Click(object sender, EventArgs e)
{
  if (!_Redirected)
  {
    // do Button1_Click() stuff...

    Response.Redirect("Button1Page.aspx", false);
    Context.ApplicationInstance.CompleteRequest();

    _Redirected = true;
  }
}

protected void Button2_Click(object sender, EventArgs e)
{
  if (!_Redirected)
  {
    // do Button2_Click() stuff...

    Response.Redirect("Button2Page.aspx", false);
    Context.ApplicationInstance.CompleteRequest();

    _Redirected = true;
  }
}
Run Code Online (Sandbox Code Playgroud)

~~~

[01/24/2013]为了回应/sf/users/169711/(谢谢你,顺便说一句),这里是简化的代码,我认为这与你测试的类似.在Page_Load()中使用.CompleteRequest()的Response.Redirect(url,false)之后,我仍然看到Button1_Click()执行回发.

protected void Page_Load(object sender, EventArgs e)
{
  if (this.IsPostBack)
  {
    Response.Redirect("Redirect.aspx", false);
    Context.ApplicationInstance.CompleteRequest();
  }
}

protected void Button1_Click(object sender, EventArgs e)
{
  Response.Write("Button1 clicked!");
}
Run Code Online (Sandbox Code Playgroud)

此响应/sf/answers/907049811/对我在上次更新中提到的类似帖子中证实了此行为.

知道我做错了会导致页面在重定向后继续执行吗?

Not*_*tMe 6

您引用了一篇非常好的文章,但您的代码并没有反映作者建议的"正确"执行此操作的方式.即:

protected void Page_Load(object sender, EventArgs e)
{
  if (Session["key"] == null)
  {
    Response.Redirect("SessionExpired.aspx", false);
    Context.ApplicationInstance.CompleteRequest();
  }       
}
Run Code Online (Sandbox Code Playgroud)

更新
我整理了一个非常简单的示例应用程序.它只有两个表格页面.
第一页上有一个按钮,它做了一个response.write.我在这一行上设置了一个断点.在page_load方法中,我进行了重定向,然后立即调用CompleteRequest.如果页面回发,则会发生此重定向.

所有第二页都发出了"你好"

然后我运行了应用程序,它提取了第一个表单.我点击了按钮.断点从未被击中并且被重定向.这正是我所期望的.即,page_load方法捕获回发,执行重定向并立即完成请求而无需进一步处理页面.

这意味着绝对没有理由将if (!_Redirected)代码放在每次按钮点击中.您需要做的就是复制/粘贴我在此答案顶部的代码.它会阻止调用这些点击.

  • 嗯,我认为无限循环可能比我试图避免的例外更糟,但谢谢,@ Earlz. (3认同)