Response.cookies和Request.cookies
Response.cookies和Request.cookies的区别很重要,由于方法基本都是差不多的,特别对于初学者而言,很容易出现混淆。
简单说就是创建cookie用response,获取cookie值用request。
下面是创建cookie的代码
方法一:
Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
方法二:使用HttpCookie类
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
以下是读取cookie值的代码
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}
Response.Cookies用于向客户端写cookie的。(输出到客户,所以定义到Response这个对象里。)
Request.Cookies用于向客户端读cookie的。(从客户端获取,所以定义到Request这个对象里。)
因为cookie是存储在客户端,所以服务器端是没法删除的,必须通知客户端去删除,一般是设计过期时间。
C#中对cookie的操作
保存cookie
HttpCookie cookie = new HttpCookie("userinfo"); cookie["userid"] = user.ID.ToString(); cookie["username"] = user.UserName; //设置cookie的保存事件 (天)为单位 cookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(cookie);
读取cookie
HttpCookie cookie = Request.Cookies["userinfo"]; int userid = int.Parse(cookie["userid"].ToString());
推荐传送门:http://www.cnblogs.com/Darren_code/archive/2011/11/24/Cookie.html
传送门:http://blog.csdn.net/u014390849/article/details/51790943