[英]How to destroy session in ASP.net when user navigates away from the page or exits the browser
I have three session that I am setting navigating from my homepage to another page, like this: 我有三个会话,我正在设置从我的主页导航到另一个页面,如下所示:
Session["LocationText"] = locText;
Session["SpecialtyText"] = speText;
Session["GenderText"] = genText;
Response.Redirect("anotherpage.aspx", false);
Once I am in anotherpage.aspx
, and either I navigate away from the page or close the browser, I would like to destroy those variable. 一旦我在
anotherpage.aspx
,并且我离开页面或关闭浏览器,我想销毁这些变量。 The whole idea is, if I come back to anotherpage.aspx
and it wasn't redirected from the page from a button click, it will not have any sessions. 整个想法是,如果我回到
anotherpage.aspx
并且没有从按钮点击页面重定向,它将没有任何会话。
I tried the following: 我尝试了以下方法:
protected void Page_Unload(object sender, EventArgs e) {
Session.Remove("LocationText");
Session.Remove("SpecialtyText");
Session.Remove("GenderText");
}
When I navigated away from the page and came back to it, it didn't destroy the variables. 当我离开页面并回到它时,它没有破坏变量。 How can I achieve what I am looking to do?
我怎样才能实现我的目标?
UPDATE : 更新 :
homepage: 主页:
Context.Items["LocationText"] = locText;
Context.Items["SpecialtyText"] = speText;
Context.Items["GenderText"] = genText;
anotherpage: anotherpage:
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();
}
Based on your question and comment, it sounds like Context
may be more appropriate than Session
. 根据您的问题和评论,听起来像
Context
可能比Session
更合适。 Variables in Context
only live for the life of the current request. Context
变量仅适用于当前请求的生命周期。
Why not use Session.Abandon()
on your Page_Unload
event. 为什么不在
Page_Unload
事件上使用Session.Abandon()
。 You can start a new session again. 您可以再次开始新会话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.