码迷,mamicode.com
首页 > 其他好文 > 详细

cookie和session是否可以保存对象

时间:2016-07-29 18:41:41      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

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>");
            }

 

cookie和session是否可以保存对象

标签:

原文地址:http://www.cnblogs.com/llcdbk/p/5719078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!