How to clear SQL session state for all users in ASP.NET

11,570

You can call Session.Abandon, or Clear for every user when they hit the invalid Session object.

You can also loop through the per-user Session collection, and clear the keys that can contain "old" objects. Maybe you have a login ticket and such that you don't want to clear.

foreach (string key in Session.Keys)
{
  if (!key.Equals("login"))
  {
    Session.Remove(key);
  }
}
Share:
11,570
German Latorre
Author by

German Latorre

Clean code enthusiast since 1998, expertising C# and ASP.NET since 2003 and loving JavaScript since 2006, I am a serious web app developer and frustrated graphical designer. I love creating beautifully structured apps with any available technology (JavaScript, C# and modern PHP, mainly), and playing with any new framework or programming language as often as I can.

Updated on July 07, 2022

Comments

  • German Latorre
    German Latorre almost 2 years

    I use SQLServer SessionState mode to store session in my ASP.NET application. It stores certain objects that are serialized/deserialized every time they are used.

    If I make any changes in code of the structure of those objects and I put a new version live, any logged user will get an error, as their session objects (the old version ones) do not match the structure that the new version expects while deserializing.

    Is there a way to clear all sessions at once in DB so that all active sessions expire and users are forced to log in again (and therefore all session objects are created from scratch)?

    Or... Is there any other way to solve this situation?