gpt4 book ai didi

c# - TempData Like Object in WebForms - 只有 1 个附加请求的 session 状态

转载 作者:太空狗 更新时间:2023-10-29 22:02:12 25 4
gpt4 key购买 nike

我想通过 session 状态仅针对一个请求存储一些对象。我似乎想不出一个简单的方法来完成这个。这正是 ASP.NET MVC 的 TempData 对象所做的。谁能给我提供一个链接或一些示例,说明如何让处于 session 状态的对象仅在一个额外请求中存活下来?

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

最佳答案

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

// 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);
}

关于c# - TempData Like Object in WebForms - 只有 1 个附加请求的 session 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1350019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com