转:http://www.cnblogs.com/wucf2004/archive/2008/08/12/1266076.html
//参考别人的方法
HttpCookie MyCo; string _strPageDomain="test.cn"; if (_strPageDomain != null && _strPageDomain != "") { MyCo = HttpContext.Current.Request.Cookies["siteinfo"]; if (System.Web.HttpContext.Current.Request.ServerVariables.ToString().IndexOf(_strPageDomain)>= 0 && MyCo != null) { MyCo.Domain = _strPageDomain; MyCo.Expires = DateTime.Now.AddHours(-24); //关键是这一句 HttpContext.Current.Response.Cookies.Add(MyCo); } } else { MyCo = HttpContext.Current.Request.Cookies["siteinfo"]; if (MyCo != null) { MyCo.Expires = DateTime.Now.AddHours(-48); HttpContext.Current.Response.Cookies.Add(MyCo); } }
// JS 方法
//删除Cookie function delCookie(_name) { var date = new Date(); date.setTime (date.getTime() - 1); document.cookie = _name + "=; path=/; expires="+ date.toGMTString(); } delCookie("userName"); /* *Cookie跨域的问题取决于domain的设置,比如一个二级域名a.zhidao123.net,另一个二级域名b.zhidao123.net要同享Cookie,那么只需设置domain=zhidao123.net即可 *所有目录共享要设置path,path=/表示将cookie设置在根目录,这样所有目录下的页面都能读到这个cookie *如果path不设置,默认的路径是当前页面的所在的目录,如果根目录和当前页面目录下有相同的cookie,则先获取当前页面所在目录的cookie */ //写入Cookie function addCookie(_name,_value,_hours) { var str = _name + "=" + escape(_value); if(_hours > 0) { var date = new Date(); var ms = _hours * 3600 * 1000; date.setTime(date.getTime() + ms); str += "; expires=" + date.toGMTString() + "; domain=zhidao123.net; path=/;"; } document.cookie = str; } addCookie("userName","Your Name",10); //读取Cookie function getCookie(_name) { var arrStr = document.cookie.split("; ");//请注意分号后面有空格,空格不能省略 for(var i = 0;i < arrStr.length;i ++) { var temp = arrStr[i].split("="); if(temp[0] == _name) return unescape(temp[1]); } } document.write(getCookie("userName"));