how to end session or logout a user on browser close MVC ASP .NET

16,801

Solution 1

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

Solution 2

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)

Solution 3

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.

Share:
16,801
SamR
Author by

SamR

Updated on June 14, 2022

Comments

  • SamR
    SamR almost 2 years

    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!

  • SamR
    SamR over 10 years
    Thank you very much, but This is not webform and I'm using MVC! where should I put the body onload on MVC?
  • Vinh
    Vinh over 10 years
    Sorry for answering you late. There is javascript, you can put in in your web page aspx. <html> <script> function del_cookie(name) { document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;'; } </script> <body onload="SetCookie()" onunload="del_cookie()"> //your content// </body> </html>
  • Rufix
    Rufix over 9 years
    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.
  • Deantwo
    Deantwo about 5 years
    Link is broken. Found it on WaybackMachine, here: web.archive.org/web/20130424221916/http://javascript.about.c‌​om/…