TempData Like Object in WebForms - Session State f

2019-06-19 01:56发布

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?

2条回答
Evening l夕情丶
2楼-- · 2019-06-19 02:17

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 count 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);
}
查看更多
We Are One
3楼-- · 2019-06-19 02:36
登录 后发表回答