Friday, August 7, 2015

Backup and Restore current session

Problem:

I was doing impersonation in my project, from one login user can insert into another person's account this is for admin mainly. here I am facing one problem when the user logged out from 2nd account then I need to repopulate the previous session of the current user. To do so I backed up the current session and store that in a single key after logged in with 2nd user and after log out from 2nd user I get the key and remove current session then restore the session.


Solution:

Backup session store that in a dictionary-
         public Dictionary<string, object> BackupSession()
        {
            Dictionary<string, object> dicSesson = new System.Collections.Generic.Dictionary<string, object>();

            for (int i = 0; i <= HttpContext.Current.Session.Count - 1; i++)
            {
                dicSesson.Add(HttpContext.Current.Session.Keys[i],  HttpContext.Current.Session[i]);
            }

            return dicSesson;
        }


Restore session keys from the dictionary-
        public void RestoreSession(Dictionary<string, object> prevSessionData)
        {
            foreach (string key in prevSessionData.Keys)
            {
                HttpContext.Current.Session[key] = prevSessionData[key];
            }
        }

No comments:

Post a Comment