自己动手写Session
一、首先我们先定义一个方法,用于创建session
public class SessionMsg//创建session { private static IDictionary<string,IDictionary<string,object>> data=new Dictionary<string,IDictionary<string,object>>(); public static IDictionary<string,object> getSession(string sessionId) { if (data.ContainsKey(sessionId)) { return data[sessionId]; } else { IDictionary<string,object> session=new Dictionary<string,object>(); data[sessionId] = session; return session;
}
}
}
二、然后我们就可以在页面加载事件中使用刚刚创建的session
protected void Page_Load(object sender, EventArgs e)//使用创建好的
{
if (Request.Cookies["sessionId"] ==null)
{
string sessionId = Guid.NewGuid().ToString();
Response.SetCookie(new HttpCookie("sessionId",sessionId));
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string sessionId = Request.Cookies["sessionId"].Value.ToString();
IDictionary<string, object> session = SessionMsg.getSession(sessionId);
session["MySession"] ="设置session的时间是:"+DateTime.Now;
}
protected void Button2_Click(object sender, EventArgs e)
{
string sessionId = Request.Cookies["sessionId"].Value;
IDictionary<string, object> session = SessionMsg.getSession(sessionId);
Button2.Text = session["MySession"].ToString();
}
}