指尖

养成无时无刻记录的习惯
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c# cookie应用 2014-04-13

Posted on 2014-04-13 15:33  指尖  阅读(112)  评论(0)    收藏  举报

//初始化 cookie

HttpCookie cookie = new HttpCookie("cai");

添加 cookie 值 汉字 用 Server.UrlEncode 编码

cookie.Values.Add("type", Server.UrlEncode(type));
          
           cookie.Values.Add("cai",dt.Rows[0][1].ToString());
           cookie.Values["mifan"] = dt.Rows[0][2].ToString();
           cookie.Values["mantou"] = dt.Rows[0][3].ToString();
           cookie.Values["zhou"] = dt.Rows[0][4].ToString();

设定值的过期时间    

cookie.Expires = DateTime.Now.AddHours(1);
      加入到cookie 集合中

Response.AppendCookie(cookie);

 

 

page_load 页面

//判断cookie是否存在

if (Request.Cookies["cai"] != null)
      {
          zhanshi.InnerHtml = "我已定:" + Server.UrlDecode(Request.Cookies["cai"]["type"]) + "  菜 " + Request.Cookies["cai"]["cai"] + "份" + "  饭 " + Request.Cookies["cai"]["mifan"] + "份" + "  馒头 " + Request.Cookies["cai"]["mantou"] + "个" + "  粥 " + Request.Cookies["cai"]["zhou"] + "份";
      }

 

//汉字解码

Server.UrlDecode(Request.Cookies["cai"]["type"])

中文cookie的问题,
   在Windows 2000正常,
   在Windows 2003 sp1下会偶尔出现乱码(遇到双字节特殊字符时候,例子:「`蹆绌 ),
   在windows 2003 SP2下基本乱码