I want a certain segment of code to be executed only once per session, so if the user navigates to the page containing this code while within the same session, I don’t want this segment to be executed. The code lives in a default page that is called right after login, and user can navigate to this default page from other pages.
My Solution:
if (Session["MySessionName"] == null && ConditionTwo) //initially MySessionName won't exist so the if condition resolves to true
{
//Assign Value to MySessionName so the if condition resolves to false next time
Session["MySessionName"] = "MySessionValue";
//Do Something
}
My Problem:
This works fine on visual studio, after deploying to test server this solution doesn’t seem to work all the time. If I log out and log back in, the condition Session["MySessionName"] == null returns false and the code segment won’t be executed. However if I close the browser, reopen, and log in, it works fine. I have checked if the logout did a proper session dispose and it does.
I also tried,
HttpContext.Current.Session["MySessionName"] = "MySessionValue";
//and
Session.Add("MysessionName", true);
but result was the same.
If you are using forms authentication, you need to call
FormsAuthentication.SignOut().In addition, on logout you need to call
Context.Session.Abandon()to terminate the current session.I also make sure that I always explicitly clear any sensitive or user-related values from the session state prior to abandoning the session.