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

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

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

我实现了一些非常类似于你在Global.ascx.cs的Application_AcquireRequestState方法中描述的内容。 我的所有会话对象都包含在一个可以计算读取次数的类中。

// clear any session vars that haven't been read in x requests List keysToRemove = new List(); 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); } 

你可以在这里找到非常相似的东西: http : //maff.ailoo.net/2009/06/build-a-flashmessenger-system-in-aspnet-mvc/