'How to correctly update database when users session expires for ASP.NET web application using the new .NET 6 format?
When a users session expires I want to update the database to switch their status to offline but I cannot find the right way to do this as I know that they can either close the browser/page or the session could expire. I'm using CookieAuthentication which has a timer of 30 minutes.
I would like some advice on the best way I can do this, either having Javascript but I don't know if this can work with C# to run a database script. I also need this per user to when the user logs in the database updates a table saying they are online and when the user logs out it also updates it saying that user is offline but obviously there is multiple ways a user can be 'Offline'.
I am new to coding in ASP.NET and using .NET Core 6. I'm just looking for some advice on the best way this can be done.
Solution 1:[1]
From How to find if ASP.NET session is expired
How to check if session is expired using ASP.NET code
We'll define expired session as situation when Session.IsNewSession is true (it is a new session), but session cookie already exists on visitor's computer from previous session. Here is a procedure that returns true if session is expired and returns false if not.
[ C# ]
public static bool IsSessionExpired() { if (HttpContext.Current.Session != null) { if (HttpContext.Current.Session.IsNewSession) { string CookieHeaders = HttpContext.Current.Request.Headers["Cookie"]; if ((null != CookieHeaders) && (CookieHeaders.IndexOf("ASP.NET_SessionId") >= 0)) { // IsNewSession is true, but session cookie exists, // so, ASP.NET session is expired return true; } } } // Session is not expired and function will return false, // could be new session, or existing active session return false; }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | gunr2171 |