在ASP.NET中重新生成SessionID

use*_*021 9 c# asp.net

请建议如何在ASP.NET中重新生成新的会话ID.如果我们使用SessionManager生成新的id,那么它不会更改Session.SessionID的值.请建议如何实现这一目标.基本上我想在放弃Session或使用SessionManager生成NewID后有一个新的Session.SessionID.

谢谢

Ale*_*lex 5

看一下SessionIDManager.SaveSessionID方法,它将新创建的会话标识符保存到HTTP响应:

SessionIDManager manager = new SessionIDManager();
var newId = manager.CreateSessionID(Context);
var isRedirected = false;
var isAdded = false;
manager.SaveSessionID(Current, newId, out isRedirected, out isAdded);
Run Code Online (Sandbox Code Playgroud)

  • 我们尝试了这个,但Session.SessionID没有采用新生成的数字.谢谢.任何帮助表示赞赏. (3认同)

小智 5

//Regenerate new Session ID after login
private void RegenerateSessionId()
{
    System.Web.SessionState.SessionIDManager manager = new System.Web.SessionState.SessionIDManager();
    string oldId = manager.GetSessionID(Context);
    string newId = manager.CreateSessionID(Context);
    bool isAdd = false, isRedir = false;
    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;
    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;
    }
    object lockId = rqLockIdField.GetValue(ssm);
    if ((lockId != null) && (oldId != null)) store.ReleaseItemExclusive(Context, oldId, lockId);
    rqStateNotFoundField.SetValue(ssm, true);
    rqIdField.SetValue(ssm, newId);
}
                //get sessionId
            string SessionId = HttpContext.Current.Session.SessionID; //new System.Web.SessionState.SessionIDManager().GetSessionID(Context);
Run Code Online (Sandbox Code Playgroud)