Cookie
对象
Cookie
对象用于保存客户端请求的服务器页面信息,数据信息是通过文本的形式保存在客户端计算机中的,客户端在每一次的请求过程中都会携带Cookie
信息并将其发送到服务器端,有一定的安全隐患。并非所有的浏览器都支持Cookie
。
Cookie
的几个关键属性
Expires
属性:设置Cookie
的过期时间Name
属性:获取和设置Cookie
的名称Value
属性:获取或设置单个Cookie
的值Values
属性:获取单个Cookie
对象所包含的键值对集合
写入和获取Cookie
数据
Cookie
的读和写都与客户端有关联,所以读操作需要借助Request
,写操作需要借助Response
通过Response
对象写入
1、通过Response.Cookies
属性返回HttpCookieCollection
类的索引器直接写入Cookie
Response.Cookies["CookieName"].Value = "CookieValue";
2、通过HttpCookie
对象设置Cookie
信息,然后将该对象的实例添加到Response.Cookies
中
HttpCookie cookie = new HttpCookie("CookieName");
cookie.Expires = DateTime.Now.AddMinutes(35); //设置过期时间为35分钟
cookie.Value = "CookieValue";
Response.Cookies.Add(cookie);
通过Request
对象读取
1、通过Request.Cookies
属性返回HttpCookieCollection
类的索引器读取
HttpCookie cookie = Request.Cookies["CookieName"];
string CookieValue = cookie.Value;
2、使用Request.Cookies
属性的Get
方法读取
HttpCookie cookie = Request.Cookies.Get("CookieName");
string CookieValue = cookie.Value;