asp.net

.net如何给cookie赋值与读取

2010-11-18

Request.Cookies读取 Response.Cookies设置

赋值
HttpCookie MyCookie = new HttpCookie("LastVisit");
DateTime now = DateTime.Now;

MyCookie.Value = now.ToString();
MyCookie.Expires = now.AddHours(1);

Response.Cookies.Add(MyCookie);

读取
Request.Cookies[""]

 

 

清除cookie有两种个方式:一个是在服务端清除,一个是在客户端清除

服务端清除cookie:
1。Request.Cookies.Remove(name);//清除指定Cookie
2.Request.Cookies.Clear();//清除所有Cookie

客服端js操作cookie
//读取cookies函数 
function getCookie(name)       
{
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
    if(arr != null) return unescape(arr[2]); return null;
}

//删除cookie
function delCookie(name)
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=NewGetCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

//添加Cookie
function setCookies(name,value)
{
    var Days = 30;
    var exp  = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}