/// <summary>
        /// Event handler for HttpApplication.AcquireRequestState
        /// </summary>
        /// <param name="source"></param>
        /// <param name="args"></param>
        private void OnAcquireRequestState(object source, EventArgs args)
        {
            acquireCalled = true;

            HttpApplication app         = (HttpApplication)source;
            HttpContext     context     = app.Context;
            bool            isNew       = false;
            SessionItem     sessionData = null;
            bool            supportSessionIdReissue;

            sessionIdManager.InitializeRequest(context, false, out supportSessionIdReissue);
            var sessionId = sessionIdManager.GetSessionID(context);


            if (sessionId != null)
            {
                sessionData = GetSessionItem(sessionId);
            }
            else
            {
                bool redirected, cookieAdded;

                sessionId = sessionIdManager.CreateSessionID(context);
                sessionIdManager.SaveSessionID(context, sessionId, out redirected, out cookieAdded);

                if (redirected)
                {
                    return;
                }
            }

            if (sessionData == null)
            {
                // Identify the session as a new session state instance. Create a new SessionItem
                // and add it to the local Hashtable.

                isNew = true;

                sessionData = AddNewSessionItem(sessionId,
                                                SessionStateUtility.GetSessionStaticObjects(context));
            }

            // Add the session data to the current HttpContext.
            SessionStateUtility.AddHttpSessionStateToContext(context,
                                                             new HttpSessionStateContainer(sessionId,
                                                                                           sessionData.Items,
                                                                                           sessionData.StaticObjects,
                                                                                           Timeout,
                                                                                           isNew,
                                                                                           CookieMode,
                                                                                           SessionStateMode.Custom,
                                                                                           false));

            // Execute the Session_OnStart event for a new session.
            if (isNew && Start != null)
            {
                Start(this, EventArgs.Empty);
            }
        }
Ejemplo n.º 2
0
        private void OnAcquireRequestState(object source, EventArgs args)
        {
            HttpApplication app     = (HttpApplication)source;
            HttpContext     context = app.Context;
            bool            isNew   = false;
            string          sessionId;

            RedisSessionItemHash sessionItemCollection = null;
            bool supportSessionIDReissue = true;

            sessionIDManager.InitializeRequest(context, false, out supportSessionIDReissue);
            sessionId = sessionIDManager.GetSessionID(context);

            if (sessionId == null)
            {
                bool redirected, cookieAdded;

                sessionId = sessionIDManager.CreateSessionID(context);
                sessionIDManager.SaveSessionID(context, sessionId, out redirected, out cookieAdded);

                isNew = true;

                if (redirected)
                {
                    return;
                }
            }

            if (!RequiresSessionState(new HttpContextWrapper(context)))
            {
                return;
            }

            releaseCalled = false;

            sessionItemCollection = new RedisSessionItemHash(sessionId, redisConfig.SessionTimeout, GetRedisConnection());

            if (sessionItemCollection.Count == 0)
            {
                isNew = true;
            }

            // Add the session data to the current HttpContext.
            SessionStateUtility.AddHttpSessionStateToContext(context,
                                                             new TaskWaitRedisHttpSessionStateContainer(sessionId,
                                                                                                        sessionItemCollection,
                                                                                                        SessionStateUtility.GetSessionStaticObjects(context),
                                                                                                        redisConfig.SessionTimeout,
                                                                                                        isNew,
                                                                                                        redisConfig.CookieMode,
                                                                                                        SessionStateMode.Custom,
                                                                                                        false));

            // Execute the Session_OnStart event for a new session.
            if (isNew && Start != null)
            {
                Start(this, EventArgs.Empty);
            }
        }
        private bool CreateSessionId()
        {
            // CreateSessionId should be called only if:
            Debug.Assert(_rqId == null ||                       // Session id isn't found in the request, OR
                         (_rqSessionStateNotFound &&            // The session state isn't found, AND
                          s_configRegenerateExpiredSessionId && // We are regenerating expired session id, AND
                          _rqSupportSessionIdReissue &&         // This request supports session id re-issue, AND
                          !_rqIdNew),                           // The above three condition should imply the session id
                                                                // isn't just created, but is sent by the request.
                         "CreateSessionId should be called only if we're generating new id, or re-generating expired one");

            bool redirected;

            _rqId = _idManager.CreateSessionID(_rqContext.ApplicationInstance.Context);
            _idManager.SaveSessionID(_rqContext.ApplicationInstance.Context, _rqId, out redirected, out _rqAddedCookie);

            return(redirected);
        }
Ejemplo n.º 4
0
        void OnAcquireRequestState(object o, EventArgs args)
        {
            Trace.WriteLine("SessionStateModule.OnAcquireRequestState (hash " + this.GetHashCode().ToString("x") + ")");
            HttpApplication application = (HttpApplication)o;
            HttpContext     context     = application.Context;

            if (!(context.Handler is IRequiresSessionState))
            {
                Trace.WriteLine("Handler (" + context.Handler + ") does not require session state");
                return;
            }
            bool isReadOnly = (context.Handler is IReadOnlySessionState);

            bool supportSessionIDReissue;

            if (idManager.InitializeRequest(context, false, out supportSessionIDReissue))
            {
                return;                 // Redirected, will come back here in a while
            }
            string sessionId = idManager.GetSessionID(context);

            handler.InitializeRequest(context);

            storeData = GetStoreData(context, sessionId, isReadOnly);

            storeIsNew = false;
            if (storeData == null && !storeLocked)
            {
                storeIsNew = true;
                sessionId  = idManager.CreateSessionID(context);
                Trace.WriteLine("New session ID allocated: " + sessionId);
                bool redirected;
                bool cookieAdded;
                idManager.SaveSessionID(context, sessionId, out redirected, out cookieAdded);
                if (redirected)
                {
                    if (supportSessionIDReissue)
                    {
                        handler.CreateUninitializedItem(context, sessionId, (int)config.Timeout.TotalMinutes);
                    }
                    context.Response.End();
                    return;
                }
                else
                {
                    storeData = handler.CreateNewStoreData(context, (int)config.Timeout.TotalMinutes);
                }
            }
            else if (storeData == null && storeLocked)
            {
                WaitForStoreUnlock(context, sessionId, isReadOnly);
            }
            else if (storeData != null &&
                     !storeLocked &&
                     storeSessionAction == SessionStateActions.InitializeItem &&
                     IsCookieLess(context, config))
            {
                storeData = handler.CreateNewStoreData(context, (int)config.Timeout.TotalMinutes);
            }

            container = CreateContainer(sessionId, storeData, storeIsNew, isReadOnly);
            SessionStateUtility.AddHttpSessionStateToContext(app.Context, container);
            if (storeIsNew)
            {
                OnSessionStart();
                HttpSessionState hss = app.Session;

                if (hss != null)
                {
                    storeData.Timeout = hss.Timeout;
                }
            }

            // Whenever a container is abandoned, we temporarily disable the expire call back.
            // So in this case we are quite sure we have a brand new container, so we make sure it works again.
            supportsExpiration = handler.SetItemExpireCallback(OnSessionExpired);
        }
Ejemplo n.º 5
0
        //</Snippet3>


        //<Snippet4>
        //
        // Event handler for HttpApplication.AcquireRequestState
        //

        private void OnAcquireRequestState(object source, EventArgs args)
        {
            HttpApplication app     = (HttpApplication)source;
            HttpContext     context = app.Context;
            bool            isNew   = false;
            string          sessionID;
            SessionItem     sessionData             = null;
            bool            supportSessionIDReissue = true;

            pSessionIDManager.InitializeRequest(context, false, out supportSessionIDReissue);
            sessionID = pSessionIDManager.GetSessionID(context);


            if (sessionID != null)
            {
                try
                {
                    pHashtableLock.AcquireReaderLock(Int32.MaxValue);
                    sessionData = (SessionItem)pSessionItems[sessionID];

                    if (sessionData != null)
                    {
                        sessionData.Expires = DateTime.Now.AddMinutes(pTimeout);
                    }
                }
                finally
                {
                    pHashtableLock.ReleaseReaderLock();
                }
            }
            else
            {
                bool redirected, cookieAdded;

                sessionID = pSessionIDManager.CreateSessionID(context);
                pSessionIDManager.SaveSessionID(context, sessionID, out redirected, out cookieAdded);

                if (redirected)
                {
                    return;
                }
            }

            if (sessionData == null)
            {
                // Identify the session as a new session state instance. Create a new SessionItem
                // and add it to the local Hashtable.

                isNew = true;

                sessionData = new SessionItem();

                sessionData.Items         = new SessionStateItemCollection();
                sessionData.StaticObjects = SessionStateUtility.GetSessionStaticObjects(context);
                sessionData.Expires       = DateTime.Now.AddMinutes(pTimeout);

                try
                {
                    pHashtableLock.AcquireWriterLock(Int32.MaxValue);
                    pSessionItems[sessionID] = sessionData;
                }
                finally
                {
                    pHashtableLock.ReleaseWriterLock();
                }
            }

            // Add the session data to the current HttpContext.
            SessionStateUtility.AddHttpSessionStateToContext(context,
                                                             new HttpSessionStateContainer(sessionID,
                                                                                           sessionData.Items,
                                                                                           sessionData.StaticObjects,
                                                                                           pTimeout,
                                                                                           isNew,
                                                                                           pCookieMode,
                                                                                           SessionStateMode.Custom,
                                                                                           false));

            // Execute the Session_OnStart event for a new session.
            if (isNew && Start != null)
            {
                Start(this, EventArgs.Empty);
            }
        }
        public string GetUser(ControllerContext context)
        {
            var httpContext = context.HttpContext;
            var request     = httpContext.Request;
            var response    = httpContext.Response;

            // Use the same user for the duration of the request.
            if (httpContext.Items.Contains(cachedHttpContextKey))
            {
                return((string)httpContext.Items[cachedHttpContextKey]);
            }

            var fallbackCookie = request.Cookies[fallbackCookieName];

            string user;

            if (httpContext.Request.IsAuthenticated)
            {
                // The user has gone from being an anonymous user to an
                // authenticated user.
                if (httpContext.Request.AnonymousID != null)
                {
                    user = httpContext.Request.AnonymousID;
                }
                else if (IsValidCookie(fallbackCookie))
                {
                    // Even though we're authenticated, the anonymous ID is
                    // used for this request because we want to grab the temp
                    // data from the previous request (when the user was
                    // unauthenticated).
                    user = fallbackCookie.Value;

                    // Expire the cookie since don't need the cookie anymore.
                    response.Cookies.Add(new HttpCookie(fallbackCookieName)
                    {
                        Expires = DateTime.UtcNow.AddYears(-1)
                    });
                }
                else
                {
                    user = GetUserFromContext(httpContext);
                }
            }
            else if (httpContext.Request.AnonymousID != null)
            {
                user = httpContext.Request.AnonymousID;
            }
            // Fallback to the current session ID only when it hasn't changed
            // since new sessions are generated until the session is actually
            // *used*. However, if you're going this route, you should probably
            // be using the default SessionStateTempDataProvider in MVC :).
            else if (httpContext.Session != null && !httpContext.Session.IsNewSession)
            {
                user = httpContext.Session.SessionID;
            }
            else if (!IsValidCookie(fallbackCookie))
            {
                // The session ID manager is used to generate a secure ID that
                // is valid for a cookie (no reason to reinvent the wheel!).
                user = sessionIdManager.CreateSessionID(httpContext.ApplicationInstance.Context);

                // Issue a new cookie identifying the anonymous user.
                response.Cookies.Add(new HttpCookie(fallbackCookieName, user)
                {
                    HttpOnly = true
                });
            }
            else
            {
                user = fallbackCookie.Value;
            }

            httpContext.Items[cachedHttpContextKey] = user;
            return(user);
        }