跨域共享Cookie

摘自:http://www.cnblogs.com/Ihaveadream/archive/2008/05/02/1178538.html

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

 1 HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[cookiename];
 2 if (cookie != null)
 3 {
 4                 cookie.Values.Clear();
 5                 SetUserCookieExpireTime(cookiename, -1);
 6                 cookie.Domain = _domain;
 7                 System.Web.HttpContext.Current.Response.Cookies.Set(cookie);
 8  }
 9 public static void SetUserCookieExpireTime(string key, int days)
10 {
11             System.Web.HttpContext.Current.Response.Cookies[key].Domain = _domain;
12             System.Web.HttpContext.Current.Response.Cookies[key].Path = _cookiepath;
13             System.Web.HttpContext.Current.Response.Cookies[key].Expires = DateTime.Now.AddDays(days);
14 }
15 

.NET 添加/更新Cookie

 1 public static void AddUserCookies(string key,string value, string cookiename, string domain)
 2 {
 3             HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[cookiename];
 4             if (cookie == null)
 5             {
 6                 cookie = new HttpCookie(cookiename);
 7                 cookie.Domain = domain;
 8                 cookie.Path = _cookiepath;
 9 
10                 cookie.Values.Add(key, value);
11                 HttpContext.Current.Response.AppendCookie(cookie);
12             }
13             else
14             {
15                 if (System.Web.HttpContext.Current.Request.Cookies[cookiename].Values[key] != null)
16                 {
17                     cookie.Values.Set(key, value);
18                 }
19                 else
20                 {
21                     cookie.Domain = domain;
22                     cookie.Path = _cookiepath;
23 
24                     cookie.Values.Add(key, value);
25                     HttpContext.Current.Response.AppendCookie(cookie);
26                 }
27             }
28 }
29 

加支付宝好友偷能量挖...


评论(0)网络
阅读(221)喜欢(0)Asp.Net/C#/WCF