使用asp.net关闭浏览器时清除会话
问题描述:
亲爱的所有人
使用asp.net和c#
dear all
how can i clear session when browser is closed using asp.net and c#
答
请参考以下步骤.
1. First create a page SessionClear.aspx and write the code to clear session
2. Then add following JavaScript code in your page or Master Page:-
<script language="javascript" type="text/javascript">
var isClose = false;
//this code will handle the F5 or Ctrl+F5 key
//need to handle more cases like ctrl+R whose codes are not listed here
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if(keycode == 116)
{
isClose = true;
}
}
function somefunction()
{
isClose = true;
}
//<![CDATA[
function bodyUnload() {
if(!isClose)
{
var request = GetRequest();
request.open("GET", "SessionClear.aspx", true);
request.send();
}
}
function GetRequest() {
var request = null;
if (window.XMLHttpRequest) {
//incase of IE7,FF, Opera and Safari browser
request = new XMLHttpRequest();
}
else {
//for old browser like IE 6.x and IE 5.x
request = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
return request;
}
//
</script>
3. Add the following code in the body tag of master page.
<body onbeforeunload="bodyUnload();" onmousedown="somefunction()">
请参阅讨论中的答案@ ^ ]
See answer in the discussion @ http://forums.asp.net/t/1116238.aspx[^]
您可以使用两个功能,
Session.Abandon()破坏会话,并触发Session_OnEnd事件.如果使用Session.Abandon(),则会丢失该特定会话,并且用户将获得一个新的会话密钥.例如,当用户注销时,您可以使用它.
Session.Clear(),如果您希望用户保留在同一会话中并重置其所有会话特定数据
您可以研究以下链接,
http://msdn.microsoft.com/en-us/library/system. web.sessionstate.httpsessionstate_members.aspx [ ^ ]
http://msdn.microsoft.com/en-us/library/ms524310.aspx [ ^ ]
You can two function,
Session.Abandon() destroys the session and the Session_OnEnd event is triggered. if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Session.Clear(), if you want that the user remaining in the same session and reset all his session specific data
You can study the following link,
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate_members.aspx[^]
http://msdn.microsoft.com/en-us/library/ms524310.aspx[^]