(原创)cookie用法详解
本节将介绍COOKIE的基本用法.
1、COOKIE原理
当客户端首次访问服务器端时
当客户端再次访问服务器端时
2、创建COOKIE
首先引用System.Web命名空间
代码
//创建一个COOKIE对象
HttpCookie myCookie = new HttpCookie("UserInfo");
//存储COOKIE值
myCookie["UserName"] = "UserName";
myCookie["UserSex"] = "UserSex";
HttpCookie myCookie = new HttpCookie("UserInfo");
//存储COOKIE值
myCookie["UserName"] = "UserName";
myCookie["UserSex"] = "UserSex";
//设置与此COOKIE相关的域名
myCookie.Domain="cnblogs.com";
//设置COOKIE的有效期
myCookie.Expires = DateTime.Now.AddDays(5);
//添加一个COOKIE到当前的web请求
Response.Cookie.Add(myCookie);
//添加一个COOKIE到当前的web请求
Response.Cookie.Add(myCookie);
3、读取COOKIE
HttpCookie myCookie = Resquest.Cookie["UserInfo"];
string userName;
if(myCookie!=null)
{
userName = myCookie["UserName"];
}
string userName;
if(myCookie!=null)
{
userName = myCookie["UserName"];
}
4、注销Cookie
HttpCookie myCookie = new HttpCookie("UserInfo");
myCookie .Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(myCookie );
myCookie .Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(myCookie );
5、如何查看本地COOKIE
首先设置隐藏文件为可见。
打开C:/Documents and Settings/当前用户/Cookies/ 就可以查看COOKIE文件!
/************************************************/
本博客内容如果是原著都会在标题后加上(原著)字样,未加者多数为转载.
/************************************************/