以下代码在新建类class1中
public class Class1
{
private static IDictionary<string, IDictionary<string, object>> data = new Dictionary<string, IDictionary<string, object>>();//新建一个字典最为session在服务端储存用户信息的容器
public static IDictionary<string, object> Getdata(string a)//一个方法通过用户传过来cookie的value来找
{
if (data.ContainsKey(a))//在字典中有cookie的value(session的id)
{
return data[a];
}
else
{
IDictionary<string, object> data1 = new Dictionary<string, object>();
data[a]=data1;
return data[a];
}
}
}
}
以下代码在cookieandsession中
public partial class cookieAndsession : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string SessionID=Guid.NewGuid().ToString();//cookie的value
if (Request.Cookies["Mysession"] == null)
{
Response.SetCookie(new HttpCookie("Mysession", SessionID));
}
}
protected void Button1_Click(object sender, EventArgs e)//设置session
{
string ID=Request.Cookies["Mysession"].Value;
IDictionary<string, object> session=Class1.Getdata(ID);
session["服务端数据"] = "嘿嘿嘿恶化";//引用类型数据的调用
}
protected void Button2_Click(object sender, EventArgs e)//获取session
{
string sessionid = Request.Cookies["Mysession"].Value;
IDictionary<string, object> session = Class1.Getdata(sessionid);
Button2.Text = Convert.ToString(session["服务端数据"]);
}
}