cookie和session是否可以保存对象

session看了一下,是可以保存对象的。语法很普通,但是cookie的话本身是只能保存string类型的信息的,这就需要先序列化,然后接收的页面反序列化后形成对象调用,为了防止乱码,需要在数据传输的时候加入编码格式,涉及到的DLL:Newtonsoft.Json.dll,一个帮助数据序列化成JSON 的组件,DEMO如下:

 Student sessionStu = new Student();
            sessionStu.sId = 001;
            sessionStu.sName = "水晶之恋";
            Session["obj"] = sessionStu;

            Student cookieStu = new Student();
            cookieStu.sId = 002;
            cookieStu.sName = "蚂蚁上树";
            var res = JsonConvert.SerializeObject(cookieStu);

            HttpCookie cookie = new HttpCookie("cobj");
            cookie.Value = HttpUtility.UrlEncode(res,Encoding.GetEncoding("UTF-8"));
            Response.Cookies.Add(cookie);

            Response.Redirect("SessionRes.aspx");

接收页面:

            if(!IsPostBack)
            {
                Student resStu = Session["obj"] as Student;
                Response.Write("session:</br>");
                Response.Write(resStu.sId.ToString() + "</br>");
                Response.Write(resStu.sName.ToString() + "</br>");


                var res = HttpUtility.UrlDecode(Request.Cookies["cobj"].Value, Encoding.GetEncoding("UTF-8"));
                var stu = JsonConvert.DeserializeObject<Student>(res);
                
                Student resStuCookie = stu;
                Response.Write("cookie:</br>");
                Response.Write(resStuCookie.sId.ToString() + "</br>");
                Response.Write(resStuCookie.sName.ToString() + "</br>");
            }

 

posted @ 2016-07-29 17:10  洛晨随风  阅读(12292)  评论(0编辑  收藏  举报