(转)ASP.NET的Cookie跨域问题
原文地址:http://www.cnblogs.com/greatverve/archive/2011/07/05/asp-net-cookie-domain.html
将Cookie的有效范围限制到域。
默认情况下,Cookie 与特定的域相关联。
例如,如果您的站点是 www.contoso.com,那么当用户向该站点请求页面时,
您编写的Cookie就被发送到服务器。(有特定路径值的Cookie除外)
如果您的站点有子域(例如 contoso.com、sales.contoso.com 和 support.contoso.com),
就可以把Cookie同特定的子域相关联。为此,需要设置Cookie的 Domain 属性,如下所示:
Response.Cookies( "domain ").Expires = DateTime.Now.AddDays(1)
Response.Cookies( "domain ").Domain = "support.contoso.com "
您也可以利用Domain属性来创建可在多个子域中共享的Cookie。例如,对域进行如下设置:
Response.Cookies( "domain ").Expires = DateTime.Now.AddDays(1)
Response.Cookies( "domain ").Domain = "contoso.com "
如:www.it100.info,在这个根域下的所有二级域名可共享Cookie,{mail.it100.info,photo.it100.info}
{
if (blURLEncode)
{
strCookieValue = System.Web.HttpContext.Current.Server.UrlEncode(strCookieValue);
}
HttpCookie objCookie = new HttpCookie(strCookieName, strCookieValue);
objCookie.Domain = strDomain; //设置Cookie的域名
System.Web.HttpContext.Current.Response.Cookies.Add(objCookie);
return true;
}
Cookie有三个属性需要注意一下:
1. Domain 域
2. Path 路径
3. Expires 过期时间
跨域操作需要设置域属性:
Response.Cookies("MyCookie").Domain = "cnblogs.com"; (这里指的是泛域名)
这样在其它二级域名下就都可以访问到了, ASP 和 ASP.NET 测试通过
虚拟目录下访问:
我在ASP端做了下测试,.NET的没试, 如果不指定Path属性, 不同虚拟目录下Cookie无法共享
将Response.Cookies("MyCookie").Path = "/" 就可以了
总的写法:
Response.Cookies("MyCookie").Domain = "cnblogs.com";
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跨域跨目录