1

I want to make all sessions null in one statement when i make logout.Can anyone tell me how to make all session null.Currently i am making Sessions null as follows:

Session["UserID"]=null; 
Session["UserName"]=null; 
Session["Photo"]=null;
Ali Afroz
  • 25
  • 2
  • 5
  • Not an exact duplicate, but the answer is probably in here: https://stackoverflow.com/q/3551178/1220550 – Peter B Sep 11 '17 at 13:03
  • 3
    Just use `Session.Clear();` Easy to find if you describe your problem correctly: you do not want to make "sessions null", you want to reset all session variables. – oerkelens Sep 11 '17 at 13:05

2 Answers2

0

This example will do the job:

Session["UserID"] = "test1 value";
Session["UserName"] = "test2 value";
Session["Photo"] = "test3 value";

foreach (string key in Session.Keys)
{
     Session.Remove(key);
}

Response.Write(Session["UserID"]);
Response.Write(Session["UserName"]);
Response.Write(Session["Photo"]);

This could have been also done using linq, like here.

var sessionsToRemove = Session.Keys.Cast<string>().ToList();
foreach (var key in sessionsToRemove)
{
    Session.Remove(key);
}
Rahul Hendawe
  • 902
  • 1
  • 14
  • 39
0

You can try this:

 HttpSessionState session = HttpContext.Current.Session;
 session.RemoveAll();
Hero
  • 177
  • 2
  • 12