c# cookie的使用,以及与javascript cookie的交互
C#:
创建:
HttpCookie cookie = new HttpCookie("regID");
cookie .Value = username;
cookie .Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
创建有子键的:
Response.Cookies["user"]["userName"] = Server.UrlEncode("大西瓜");//使用UrlEncode是为了使用javascript取出时不是乱码
或:
HttpCookie cookie=new HttpCookie("user");
cookie.Values["userName"] = "aaa"; //cookie.Values.Add("userName","aaa");
cookie .Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie) //Response.AppendCookie(cookie) ;
消除:直接删除没法删,因为COOKIE创建以后就保存在用户机器上了而不是在服务端
这样全部删除:
private HttpCookie cookie = null;
private string cookieName = string.Empty;
for (int i = 0; i < Request.Cookies.Count; i++)
{
cookieName = Request.Cookies[i].Name;
cookie = new HttpCookie(cookieName);
cookie .Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie );
}
删除子键:
HttpCookie cookie;
cookie = Request.Cookies["userInfo"];
cookie .Values.Remove("userName");
cookie .Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
使用javascript 获得 cookie:
function get_head_cookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1)
{
c_end=document.cookie.length;
}
return decodeURIComponent(myreplace_head(document.cookie.substring(c_start,c_end),'+',' '));
}
}
return null;
}
var email = get_head_cookie('regID');
var nickname = get_head_cookie('userName');
if(email != '' && email != null && nickname != '' && nickname != null)
{
//cookie存在的情况
}
else
{
//cookie为空的情况
}