TempData类似于WebForms中的对象 - 仅一个附加请求的会话状态

Rya*_*man 6 c# asp.net-mvc session webforms

我想通过会话状态仅为一个请求存储一些对象.我似乎无法想到一个简单的方法来实现这一目标.这正是 ASP.NET MVC的TempData对象所做的.任何人都可以向我提供一个链接或一些如何让一个对象处于会话状态的例子只能存活一个额外的请求吗?

我在想,这可以通过制作一个自定义字典对象来实现,该对象存储每个项目的年龄(请求数).通过订阅Application_BeginRequest和Application_EndRequest方法,您可以执行所需的对象清理.这甚至可能有助于创建一个存储X请求数据的对象,而不仅仅是一个.这是正确的轨道吗?

Ada*_*dam 2

我实现的内容与您在 Global.ascx.cs 的 Application_AcquireRequestState 方法中描述的内容非常相似。我的所有会话对象都包装在一个类中,该类记录读取次数。

// 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);
}
Run Code Online (Sandbox Code Playgroud)