时间:2021-07-01 10:21:17 帮助过:11人阅读
Response.Cookies("MyCookie").Domain = "jb51.net";
Response.Cookies("MyCookie").Path = "/"
Response.Cookies("MyCookie").Expires = Now + 365;
Response.Cookies("MyCookie")("Test") = "test";
.NET 清除Cookie
代码如下:
HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[cookiename];
if (cookie != null)
{
cookie.Values.Clear();
SetUserCookieExpireTime(cookiename, -1);
cookie.Domain = _domain;
System.Web.HttpContext.Current.Response.Cookies.Set(cookie);
}
public static void SetUserCookieExpireTime(string key, int days)
{
System.Web.HttpContext.Current.Response.Cookies[key].Domain = _domain;
System.Web.HttpContext.Current.Response.Cookies[key].Path = _cookiepath;
System.Web.HttpContext.Current.Response.Cookies[key].Expires = DateTime.Now.AddDays(days);
}
.NET 添加/更新Cookie
代码如下:
public static void AddUserCookies(string key,string value, string cookiename, string domain)
{
HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[cookiename];
if (cookie == null)
{
cookie = new HttpCookie(cookiename);
cookie.Domain = domain;
cookie.Path = _cookiepath;
cookie.Values.Add(key, value);
HttpContext.Current.Response.AppendCookie(cookie);
}
else
{
if (System.Web.HttpContext.Current.Request.Cookies[cookiename].Values[key] != null)
{
cookie.Values.Set(key, value);
}
else
{
cookie.Domain = domain;
cookie.Path = _cookiepath;
cookie.Values.Add(key, value);
HttpContext.Current.Response.AppendCookie(cookie);
}
}
}
身份验证Cookie域,什么意思?
默认情况下,Cookie 与特定的域相关联。例如,如果您的站点是 www.gxlcms.com,那么当用户向该站点请求页面时,您编写的 Cookie 就被发送到服务器。(有特定路径值的 Cookie 除外。) 如果您的站点有子域(例如 jb51.net、s.jb51.net 和 tools.jb51.net),就可以把 Cookie 同特定的子域相关联。为此,需要设置 Cookie 的 Domain 属性,如下所示:
代码如下:
Response.Cookies("domain").Value = DateTime.Now.ToString
Response.Cookies("domain").Expires = DateTime.Now.AddDays(1)
Response.Cookies("domain").Domain = "s.jb51.net"
如果按照这种方式设置域,则 Cookie 只能用于指定子域中的页面。
您也可以利用 Domain 属性来创建可在多个子域中共享的 Cookie。例如,对域进行如下设置:
代码如下:
Response.Cookies("domain").Value = DateTime.Now.ToString
Response.Cookies("domain").Expires = DateTime.Now.AddDays(1)
Response.Cookies("domain").Domain = "jb51.net"
这样,该 Cookie 就可用于主域、s.jb51.net 和 tools.jb51.net。