壹佰网|ERP100 - 企业信息化知识门户

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 2471|回复: 0

[其他] Cookie跨域、虚拟目录, 实现通行证登录_ASP.NET

[复制链接]
发表于 2011/11/2 14:20:22 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。如果您注册时有任何问题请联系客服QQ: 83569622  。

您需要 登录 才可以下载或查看,没有帐号?注册

x

来自绿色BI社区,原文链接:http://www.powerbibbs.com/thread-4996-1-1.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
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跨域跨目录



该贴已经同步到 bjourway的微博
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|Archiver|小黑屋|手机版|壹佰网 ERP100 ( 京ICP备19053597号-2 )

Copyright © 2005-2012 北京海之大网络技术有限责任公司 服务器托管由互联互通
手机:13911575376
网站技术点击发送消息给对方83569622   广告&合作 点击发送消息给对方27675401   点击发送消息给对方634043306   咨询及人才点击发送消息给对方138011526

GMT+8, 2025/11/29 06:32 , Processed in 0.012430 second(s), 14 queries , File On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表