Reputation: 49
I have asp.net webforms application/ And what i need to do is to change ASP.NET_SessionId when user logs in.
When user logs in I execute the following code:
SessionIDManager Manager = new SessionIDManager();
string NewID = Manager.CreateSessionID(Context);
bool redirected = false;
bool IsAdded = false;
Manager.SaveSessionID(Context, NewID, out redirected, out IsAdded);
So, SessionId is changing after that.
But, then after that if I write some session variables, for example
Session["username"] = username;
then after postback our data is lost or associated with old session id. and we have
Session["username"] == null
Please can you help me how to write to session variable after changing SessionId so that data will not be lost?
Upvotes: 3
Views: 2717
Reputation: 151
Command "Manager.SaveSessionID" will remove all data of old sessionid. There is only one way to keep data. It's manual move data. You use the function below into login button:
...
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);
}
}
Upvotes: 5