【问题标题】:How to destroy session in ASP.net when user navigates away from the page or exits the browser当用户离开页面或退出浏览器时如何在 ASP.net 中销毁会话
【发布时间】:2014-05-20 00:39:33
【问题描述】:

我设置了三个会话,从我的主页导航到另一个页面,如下所示:

Session["LocationText"] = locText;
Session["SpecialtyText"] = speText;
Session["GenderText"] = genText;

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

一旦我进入anotherpage.aspx,我要么离开页面,要么关闭浏览器,我想销毁这些变量。整个想法是,如果我回到 anotherpage.aspx 并且它没有通过单击按钮从页面重定向,它将不会有任何会话。

我尝试了以下方法:

protected void Page_Unload(object sender, EventArgs e) {
    Session.Remove("LocationText");
    Session.Remove("SpecialtyText");
    Session.Remove("GenderText");
}

当我离开页面并返回时,它并没有破坏变量。我怎样才能实现我想要做的事情?

更新

主页:

Context.Items["LocationText"] = locText;
Context.Items["SpecialtyText"] = speText;
Context.Items["GenderText"] = genText;

另一页:

if (Context.Items["LocationText"] != null && Context.Items["SpecialtyText"] != null && Context.Items["GenderText"] != null) {
    slcLocation.SelectedValue = Context.Items["LocationText"].ToString();
    slcSpecialty.SelectedValue = Context.Items["SpecialtyText"].ToString();
    slcGender.SelectedValue = Context.Items["GenderText"].ToString();
    this.onBtnClick();
}

【问题讨论】:

  • "整个想法是,如果我回到 anotherpage.aspx,它不会有任何会话。"那么为什么首先将它们存储在会话中呢?
  • 因为 anotherpage.aspx 使用这些会话变量来进行搜索查询。
  • 尝试使用Context 而不是Session。这似乎更适合您的用例。
  • 我是PHP背景,请举个例子:)

标签: c# asp.net session session-variables


【解决方案1】:

为什么不在您的Page_Unload 事件中使用Session.Abandon()。您可以重新开始一个新会话。

【讨论】:

  • 这是我最初的计划,但似乎 Context.Items() 更好?
  • @SearchForKnowledge,很高兴它有帮助。然后是时候接受答案了:)。
  • 无论用户是离开还是关闭浏览器窗口,这都会起作用?
  • @SearchForKnowledge,关闭浏览器窗口无论如何都会删除会话,是的,当有人离开时它会起作用。另外,您也可以使用session.clear() 方法。
  • 感谢您的及时回复。
【解决方案2】:

根据您的问题和评论,听起来Context 可能比Session 更合适。 Context 中的变量仅在当前请求的生命周期内有效。

【讨论】:

  • 我试图用 Context.Items 替换 Session 但它没有用。 ://
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 2011-03-11
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-05
相关资源
最近更新 更多