2

I have designed a MVC Form and would like to end the session when user closes the browser and if re-open the browser, then has to log in again!

I don't know if I have to end session or clear cookies and if so, how should i do it. Will you help me to find my answer...

Thank you!

tereško
  • 58,060
  • 25
  • 98
  • 150
SamR
  • 517
  • 3
  • 10
  • 24
  • 2
    There is no fool proof way to determine if someone closed a browser or not. Also, logins are handled via cookie not session state. Here is an example thread on a similar subject - http://stackoverflow.com/questions/1783302/clear-cookies-on-browser-close – Tommy Nov 06 '13 at 06:33
  • @Tommy thank you for your answer, how and where should i clear the cookie? – SamR Nov 06 '13 at 06:45

3 Answers3

3

If you are using In-Proc Session Mode, in that case you can get Session Timeout Event in the global.asax file. So if you are creating Cookies and other user specific stubs , you can clean those thing using this event.

In Global.asax.cs

    protected void Session_End(object sender, EventArgs e)
{
   //Clean-up Code
}

In case of Out-Proc Mode you will never get Session timeout event.

As Tommy said that there is no fool proof way to determine if someone closed a browser, But you can do it by Jquery. You need to ping your server at specific time intervals. So when you stop getting anything from the client after specific time duration , you can perform cleaning operation (Same like session timeout)

Tommy
  • 39,592
  • 10
  • 90
  • 121
Pavan Tiwari
  • 3,077
  • 3
  • 31
  • 71
3

You can use:

function del_cookie(name) {
    document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
}
<body onload="SetCookie()" onunload="del_cookie()">

source here

try modify it yourself

Deantwo
  • 1,113
  • 11
  • 18
Vinh
  • 73
  • 6
  • Thank you very much, but This is not webform and I'm using MVC! where should I put the body onload on MVC? – SamR Nov 06 '13 at 19:35
  • 1
    Sorry for answering you late. There is javascript, you can put in in your web page aspx. ` //your content// ` – Vinh Nov 07 '13 at 01:41
  • 1
    It's really cool solution, but also works on tab close. So if you are working on multiple tabs it will terminate session for all of them. – Rufix Sep 25 '14 at 08:18
  • Link is broken. Found it on WaybackMachine, here: https://web.archive.org/web/20130424221916/http://javascript.about.com/library/bldelck.htm – Deantwo May 15 '19 at 14:27
1

You can try . On browser close or page onload event delete the cookies from javascript or on browser close event (or page unload event) make a call on server and CLear the session on server.

Saurabh Mahajan
  • 2,937
  • 7
  • 25
  • 32