zoukankan      html  css  js  c++  java
  • Cookie跨子域、虚拟目录, 实现通行证登录

    Cookie跨子域、虚拟目录, 实现通行证登录

    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跨域跨目录, 有不足之处望指正

  • 相关阅读:
    【高级内部资料】.NET数据批量写入性能分析 第二篇
    负载均衡原理与实践详解 第五篇 负载均衡时数据包流程详解
    负载均衡原理与实践详解 第三篇 服务器负载均衡的基本概念网络基础
    如何提高Linq查询的性能(上)
    【全面解析DeepZoom 之二】Silverlight2及Deep Zoom环境的搭建
    关于让WPF软件界面支持全球化和本地化
    在WPF中自定义控件(3) CustomControl (上)
    【全面解析DeepZoom 之一】酷!Deep Zoom
    谈谈我理解的WPF团队模型——在UI Designer与Developer之间
    [WPF疑难]在WPF中显示动态GIF
  • 原文地址:https://www.cnblogs.com/tong775131501/p/4110266.html
Copyright © 2011-2022 走看看