HttpCookie 类获取和设置各 Cookie 的属性。 HttpCookieCollection 类提供存储、检索和管理多个 Cookie 的方法。
ASP.NET 包含两个内部 Cookie 集合。通过 HttpRequest 对象的 Cookies 集合访问的集合,包含以 Cookie 标头形式由客户端传输到服务器的 Cookie。通过 HttpResponse 对象的 Cookies 集合访问的集合包含一些新 Cookie,这些 Cookie 在服务器上创建并以 Set-Cookie HTTP 响应标头的形式传输到客户端。
Request: 以 Cookie 标头形式由客户端传输到服务器的 Cookie
Response: Set-Cookie HTTP 响应标头的形式传输到客户端。
以前总是使用Session,现在也学着使用Cookies了,什么时候使用谁好就使用谁呗。
Response.Cookie("username").value="oys" 写入
username=Request.Cookies("username").value 读取
用SESSION比较方便
session("username")="oys" 写入
username=session("username") 读取
C# :
方法1:
Response.Cookies["username"].Value="oys";
Response.Cookies["username"].Expires=DateTime.Now.AddDays(1); //设置cookies的过期时间为1天
方法2:
System.Web.HttpCookie newcookie=new HttpCookie("username");
newcookie.Value="oys";
newcookie.Expires=DateTime.Now.AddDays(1);
Response.AppendCookie(newcookie);
创建带有子键的cookies:
System.Web.HttpCookie newcookie=new HttpCookie("user");
newcookie.Values["username"]="oys";
newcookie.Values["password"]="123";
newcookie.Expires=DateTime.Now.AddDays(1);
Response.AppendCookie(newcookie);
cookies的读取:
无子键读取:
if(Request.Cookies["username"]!=null)
{
Response.Write(Server.HtmlEncode(Request.Cookies["username"].Value));
}
有子键读取:
if(Request.Cookies["user"]!=null)
{
HttpCookie user = Request.Cookies["user"];
string username = user.Values["username"];
Response.Write(Server.HtmlEncode(Request.Cookies["user"].Values["username"]));
}
实例:
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
// Get cookie from the current request.
HttpCookie cookie = Request.Cookies.Get("DateCookieExample");
// Check if cookie exists in the current request.
if (cookie == null)
{
sb.Append("Cookie was not received from the client. ");
sb.Append("Creating cookie to add to the response. <br/>");
// Create cookie.
cookie = new HttpCookie("DateCookieExample");
// Set value of cookie to current date time.
cookie.Value = DateTime.Now.ToString();
// Set cookie to expire in 10 minutes.
cookie.Expires = DateTime.Now.AddMinutes(10d);
// Insert the cookie in the current HttpResponse.
Response.Cookies.Add(cookie);
}
else
{
sb.Append("Cookie retrieved from client. <br/>");
sb.Append("Cookie Name: " + cookie.Name + "<br/>");
sb.Append("Cookie Value: " + cookie.Value + "<br/>");
sb.Append("Cookie Expiration Date: " +
cookie.Expires.ToString() + "<br/>");
}
Label1.Text = sb.ToString();
}