Click here to Skip to main content
15,892,697 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
dear all

how can i clear session when browser is closed using asp.net and c#
Posted
Comments
BobJanova 28-Jun-11 6:27am    
You CANNOT reliably detect this. Do not rely on any of the JS-related approaches. If the user's network connection drops or the process is killed, you will never get a notification.

Please refer the below steps.
XML
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()">
 
Share this answer
 
v4
See answer in the discussion @ http://forums.asp.net/t/1116238.aspx[^]
 
Share this answer
 
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[^]
 
Share this answer
 
Comments
Toniyo Jackson 28-Jun-11 6:07am    
He wanted to clear the session when browser closed!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900