有时候远程服务器不允许修改session时长,而且服务器session时长过短,可以通过代码来实现动态修改、保存和恢复。
下面是几个必要的模块:
public void ResetSession()
{
RegenerateSessionId();
SessionRestore();
Session.Timeout = 120;
}
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(System.Reflection.BindingFlags.NonPublic | System.Reflection.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);
}
public void SessionBackup(string cuid)
{
string cSession = "";
string cAdd = "";
foreach (string obj in Session.Contents)
{
if (Session[obj] != null)
{
string cc = Session[obj].ToString();
if (String.IsNullOrEmpty(cc))
cc = "_$_$_";
cSession = cSession + cAdd + obj + "," + Session[obj].ToString() + "," + Session[obj].GetType().ToString();
cAdd = "@";
}
}
DataBase db = new DataBase();
db.ExecuteSingleSQL("update users set session='" + cSession + "' where userid='" + cuid + "'");
}
public void SessionRestore()
{
HttpCookie readcookie = Request.Cookies["userid"];
string cuid = readcookie.Value.ToString();
DataBase db = new DataBase();
DataSet ds = db.GetDataSet("select session from users where userid='" + cuid + "'");
if (ds.Tables[0].Rows.Count > 0)
{
string cSession = ds.Tables[0].Rows[0].ItemArray[0].ToString();
string[] a_1 = cSession.Split('@');
for (int i = 0; i < a_1.Length; i++)
{
string[] a_2 = a_1[i].Split(',');
if (a_2[1] == "_$_$_") a_2[1] = "";
if (a_2[2].IndexOf("Int") >= 0)
Session[a_2[0]] = int.Parse(a_2[1]);
else
Session[a_2[0]] = a_2[1];
}
}
}