views:

144

answers:

2

I would like to store some objects only for one request through the session state. I can't seem to think of an easy way to accomplish this. This is exactly what ASP.NET MVC's TempData object does. Could anyone provide me with a link or some examples of how to have an object in session state only survive one additional request?

I was thinking, this could be possibly accomplished by making a custom dictionary object, which stores an age (# of requests) on each item. By subscribing to the Application_BeginRequest and Application_EndRequest methods, you could perform the required cleanup of the objects. This could even probably facilitate making an object that stored a piece of data for X requests, not just one. Is this on the right track?

A: 

You can find something very similar here : http://maff.ailoo.net/2009/06/build-a-flashmessenger-system-in-aspnet-mvc/

Jitka Dařbujanová
+1  A: 

I implemented something very similar to what you describe in the Application_AcquireRequestState method of Global.ascx.cs. All my session objects are wrapped in a class that keeps could of the number of reads..

// clear any session vars that haven't been read in x requests
        List<string> keysToRemove = new List<string>();
        for (int i = 0; HttpContext.Current.Session != null && i < HttpContext.Current.Session.Count; i++)
        {
            var sessionObject = HttpContext.Current.Session[i] as SessionHelper.SessionObject2;
            string countKey = "ReadsFor_" + HttpContext.Current.Session.Keys[i];
            if (sessionObject != null/* && sessionObject.IsFlashSession*/)
            {
                if (HttpContext.Current.Session[countKey] != null)
                {
                    if ((int)HttpContext.Current.Session[countKey] == sessionObject.Reads)
                    {
                        keysToRemove.Add(HttpContext.Current.Session.Keys[i]);
                        continue;
                    }
                }
                HttpContext.Current.Session[countKey] = sessionObject.Reads;
            }
            else if (HttpContext.Current.Session[countKey] != null)
            {
                HttpContext.Current.Session.Remove(countKey);
            }
        }

        foreach (var sessionKey in keysToRemove)
        {
            string countKey = "ReadsFor_" + sessionKey;
            HttpContext.Current.Session.Remove(sessionKey);
            HttpContext.Current.Session.Remove(countKey);
        }
Adam

related questions