下面是写入cookie的代码
- HttpCookie cookie = new HttpCookie("username");
- cookie.Value = "张三,14,images/1.jpg";
- cookie.Expires = DateTime.Now.AddDays(1);
- Response.Cookies.Add(cookie);
HttpCookie cookie = new HttpCookie("username");
cookie.Value = "张三,14,images/1.jpg";
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
下面是读取cookie的代码
- if (Request.Cookies["username"]!=null)
- {
- string username = Request.Cookies["username"].Value;
- Response.Write(username);
- }
if (Request.Cookies["username"]!=null)
{
string username = Request.Cookies["username"].Value;
Response.Write(username);
}
有时读取出来的cookie值中的中文部分可能是乱码,不管是有什么导致的,我们都可以通过编码进行解决
更改上面写入cookie的代码
- HttpCookie cookie = new HttpCookie("username");
- cookie.Value = HttpUtility.UrlEncode("张三,14,images/1.jpg",Encoding.GetEncoding("UTF=8"));
- cookie.Expires = DateTime.Now.AddDays(1);
- Response.Cookies.Add(cookie);
HttpCookie cookie = new HttpCookie("username");
cookie.Value = HttpUtility.UrlEncode("张三,14,images/1.jpg",Encoding.GetEncoding("UTF=8"));
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
更改上面读取cookie的代码
- if (Request.Cookies["username"]!=null)
- {
- string username =HttpUtility.UrlDecode(Request.Cookies["username"].Value,Encoding.GetEncoding("UTF-8"));
- Response.Write(username);
- }
例子2
cookie存中文
1 cookie存取: 2 存: Cookie cookie = new Cookie("title",URLEncoder.encode("标题","utf-8")) 3 cookie.setMaxAge(365 * 24 * 60 * 60); 4 response.addCookie(cookie); 5 取: Cookie[] cookies = request.getCookies(); 6 Cookie sCookie = null; 7 String cookievalue=""; 8 for(int i = 0; i < cookies.length; i++){ 9 sCookie = cookies[i]; 10 if(sCookie.getName()!=null&&sCookie.getName().equals("title")) 11 cookievalues=URLDecoder.decode(sCookie.getValue(),"utf-8"); 12 }