Cookies有很多名字,HTTP Cookie, Web Cookie, Browser Cookie, Session Cookie等。
在网站开发的过程中,很多初学者其实滥用了它。
它的正确意义在于,它是在用于存储网站用户的个人数据的,什么时候存储呢?
在客户端和服务器处于未连接状态时候存的,也就是存在本地的脱机数据。
事实上,Cookie就是服务器发给客户端存在本地的小规模文本。
使用场景:
用户认证,会话认证,用户偏好设置,购物车数据,或者其它能够传输文本的业务。
创建Cookie:
方法1(使用HttpCookie类):
//First Way HttpCookie StudentCookies = new HttpCookie("StudentCookies"); StudentCookies.Value = TextBox1.Text; StudentCookies.Expires = DateTime.Now.AddHours(1); Response.Cookies.Add(StudentCookies);
方法2(直接使用Response):
//Second Way Response.Cookies["StudentCookies"].Value = TextBox1.Text; Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);
在一个Cookie中存储多个值:
//Writing Multiple values in single cookie Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text; Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu"; Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar"; Response.Cookies["StudentCookies"]["LastName"] = "Vatsa"; Response.Cookies["StudentCookies"]["TotalMarks"] = "499"; Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);
获取Cookie的值:
单个值:
string roll = Request.Cookies["StudentCookies"].Value;
多个值:
//For Multiple values in single cookie string roll; roll = Request.Cookies["StudentCookies"]["RollNumber"]; roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"]; roll = roll + " " + Request.Cookies["StudentCookies"]["MiddleName"]; roll = roll + " " + Request.Cookies["StudentCookies"]["LastName"]; roll = roll + " " + Request.Cookies["StudentCookies"]["TotalMarks"]; Label1.Text = roll;
删除Cookie:
if (Request.Cookies["StudentCookies"] != null) { Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1); Response.Redirect("Result.aspx"); //to refresh the page }
Now, fish! Can you use the cookie correctly?