Example #1
0
        public Dictionary <string, object> GetSession(ICurrentContext context)
        {
            var     sessionId = context.Request.Cookies["session"];
            Session session;
            var     now     = DateTime.Now;
            var     expires = now.AddHours(1);

            if (sessionId == null || !sessions.ContainsKey(sessionId))
            {
                lock (sessions)
                {
                    if (sessionId == null || !sessions.ContainsKey(sessionId))
                    {
                        //Prune expired sessions
                        foreach (var key in sessions.Where(s => s.Value.Expires < now).Select(s => s.Key).ToList())
                        {
                            sessions.Remove(key);
                        }

                        do
                        {
                            var generate = new byte[10];
                            var rand     = new Random();
                            rand.NextBytes(generate);
                            sessionId = Convert.ToBase64String(generate);
                        }while (sessions.ContainsKey(sessionId));
                        session = new Session {
                            Content = new Dictionary <string, object>()
                        };
                        sessions[sessionId] = session;
                    }
                }
            }

            context.SetCookie("session", sessionId, new CookieOptions {
                Expires = expires
            });

            session         = sessions[sessionId];
            session.Expires = expires;
            return(session.Content);
        }