how to end session or logout a user on browser close MVC ASP .NET
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.
SamR
Updated on June 14, 2022Comments
-
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 over 10 yearsThank you very much, but This is not webform and I'm using MVC! where should I put the body onload on MVC?
-
Vinh over 10 yearsSorry 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 over 9 yearsIt'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 about 5 yearsLink is broken. Found it on WaybackMachine, here: web.archive.org/web/20130424221916/http://javascript.about.com/…