gpt4 book ai didi

asp.net - 更改 session 变量中的 SessionID 数据后会丢失

转载 作者:行者123 更新时间:2023-12-02 06:26:22 28 4
gpt4 key购买 nike

我有 asp.net webforms 应用程序/我需要做的是在用户登录时更改 ASP.NET_SessionId。

当用户登录时,我执行以下代码:

SessionIDManager Manager = new SessionIDManager();
string NewID = Manager.CreateSessionID(Context);
bool redirected = false;
bool IsAdded = false;
Manager.SaveSessionID(Context, NewID, out redirected, out IsAdded);

因此,SessionId 之后会发生变化。

但是,之后如果我写一些 session 变量,例如

Session["username"] = username;

然后回发后我们的数据会丢失或与旧 session ID 相关联。我们有

Session["username"] == null

请帮我看看如何在更改 SessionId 后写入 session 变量以使数据不会丢失?

最佳答案

命令“Manager.SaveSessionID”将删除旧sessionid的所有数据。只有一种方法可以保存数据。这是手动移动数据。您可以在登录按钮中使用以下功能:

...
using System.Web.SessionState;
using System.Reflection;

protected void ReGenerateSessionId()
{
SessionIDManager manager = new SessionIDManager();
string oldId = manager.GetSessionID(Context);
string newId = manager.CreateSessionID(Context);
bool isAdd = false, isRedir = false;
manager.RemoveSessionID(Context);
manager.SaveSessionID(Context, newId, out isRedir, out isAdd);

HttpApplication ctx = (HttpApplication)HttpContext.Current.ApplicationInstance;
HttpModuleCollection mods = ctx.Modules;
System.Web.SessionState.SessionStateModule ssm = (SessionStateModule)mods.Get("Session");
System.Reflection.FieldInfo[] fields = ssm.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
SessionStateStoreProviderBase store = null;
System.Reflection.FieldInfo rqIdField = null, rqLockIdField = null, rqStateNotFoundField = null;

SessionStateStoreData rqItem = null;
foreach (System.Reflection.FieldInfo field in fields)
{
if (field.Name.Equals("_store")) store = (SessionStateStoreProviderBase)field.GetValue(ssm);
if (field.Name.Equals("_rqId")) rqIdField = field;
if (field.Name.Equals("_rqLockId")) rqLockIdField = field;
if (field.Name.Equals("_rqSessionStateNotFound")) rqStateNotFoundField = field;

if ((field.Name.Equals("_rqItem")))
{
rqItem = (SessionStateStoreData)field.GetValue(ssm);
}
}
object lockId = rqLockIdField.GetValue(ssm);

if ((lockId != null) && (oldId != null))
{
store.RemoveItem(Context, oldId, lockId, rqItem);
}

rqStateNotFoundField.SetValue(ssm, true);
rqIdField.SetValue(ssm, newId);
}

protected void Login_Click(object sender, EventArgs e)
{
if (/*Login success*/)
{
ReGenerateSessionId(); // Change SessionID
Session["User"] = user;
Response.Redirect("Login_Success.aspx", true);
}
}

关于asp.net - 更改 session 变量中的 SessionID 数据后会丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15241464/

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