js无法获取.net设置的cookie

使用CookieHelper帮助类:

public class CookieHelper
    {

        #region 获取Cookie


        /// <summary> 
        /// 获得Cookie的值 
        /// </summary> 
        /// <param name="cookieName"></param> 
        /// <returns></returns> 
        public static string GetCookieValue(string cookieName)
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request != null)
                return GetCookieValue(request.Cookies[cookieName]);
            return "";
        }

        /// <summary> 
        /// 获得Cookie的值 
        /// </summary> 
        /// <param name="cookie"></param> 
        /// <returns></returns> 
        public static string GetCookieValue(HttpCookie cookie)
        {
            if (cookie != null)
            {
                return cookie.Value;
            }
            return "";
        }

        /// <summary> 
        /// 获得Cookie 
        /// </summary> 
        /// <param name="cookieName"></param> 
        /// <returns></returns> 
        public static HttpCookie GetCookie(string cookieName)
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request != null)
                return request.Cookies[cookieName];
            return null;
        }

        #endregion

        #region 删除Cookie


        /// <summary> 
        /// 删除Cookie
        /// </summary> 
        /// <param name="cookieName"></param> 
        public static void RemoveCookie(string cookieName)
        {
            HttpResponse response = HttpContext.Current.Response;
            if (response != null)
            {
                HttpCookie cookie = response.Cookies[cookieName];
                if (cookie != null)
                {
                     response.Cookies.Remove(cookieName);
                }
            }
        }

        #endregion

        #region 设置/修改Cookie
         

        /// <summary> 
        /// 设置Cookie 
        /// </summary> 
        /// <param name="cookieName"></param> 
        /// <param name="key"></param> 
        /// <param name="value"></param> 
        /// <param name="expires"></param> 
        public static void SetCookie(string cookieName,string value, DateTime? expires)
        {
            Guard.IsNotNullOrEmpty(cookieName, "cookieName"); 

            HttpResponse response = HttpContext.Current.Response;
            if (response != null)
            {
                HttpCookie cookie = response.Cookies[cookieName];
                if (cookie != null)
                {
                    cookie.Value = value; 
                    if (expires != null)
                        cookie.Expires = expires.Value;
                    response.SetCookie(cookie);
                }
            }

        }

        #endregion

        #region 添加Cookie
         
         

        /// <summary> 
        /// 添加为Cookie.Values集合 
        /// </summary> 
        /// <param name="cookieName"></param> 
        /// <param name="key"></param> 
        /// <param name="value"></param> 
        /// <param name="expires"></param> 
        public static void AddCookie(string cookieName,  string value, DateTime expires)
        {
            Guard.IsNotNullOrEmpty(cookieName, "cookieName");

            HttpCookie cookie = new HttpCookie(cookieName);
            cookie.Expires = expires;
            cookie.Value = value;
            AddCookie(cookie);
        }

        /// <summary> 
        /// 添加Cookie 
        /// </summary> 
        /// <param name="cookie"></param> 
        public static void AddCookie(HttpCookie cookie)
        {
            HttpResponse response = HttpContext.Current.Response;
            if (response != null)
            {
                //指定客户端脚本是否可以访问[默认为false] 
                cookie.HttpOnly = true;
                //指定统一的Path,比便能通存通取 
                cookie.Path = "/";
                //设置跨域,这样在其它二级域名下就都可以访问到了 
                //cookie.Domain = "nas.com"; 
                response.AppendCookie(cookie);
            }
        }

        #endregion
    }

设置cookie:

   public static string VCLoginName
        {
            get
            {
                try
                {
                    return CookieHelper.GetCookieValue("VCLoginName").ToStr();
                }
                catch
                {
                    return "0";
                }
            }
            set
            {
                var cookie = CookieHelper.GetCookie("VCLoginName");
                if (cookie != null)
                {
                    CookieHelper.SetCookie("VCLoginName", value, DateTime.Now.AddHours(1));
                }
                else
                {
                    //有效期,一个钟头
                    CookieHelper.AddCookie("VCLoginName", value, DateTime.Now.AddHours(1));
                }

            }
        }

设置:

 SysContext.VCLoginName = user.LoginName;

js获取和设置cookie:

 function getCookie(cname) {
            console.log("开始")
            console.log(document.cookie)
            console.log("结束")
            var arrStr = document.cookie.split("; ");
           
            for (var i = 0; i < arrStr.length; i++) {

                var temp = arrStr[i].split("=");

                if (temp[0] == cname) return unescape(temp[1]);

            }

        }

 //添加cookie
        function addCookie(cname, cvalue, ctime) {
            var str = cname + "=" + escape(cvalue);
            if (ctime > 0) {                               //为时不设定过期时间,浏览器关闭时cookie自动消失
                var date = new Date();
                var ms = ctime * 3600 * 1000;
                date.setTime(date.getTime() + ms);
                str += "; expires=" + date.toGMTString();
                alert(cname + cvalue);
            }
            document.cookie = str;
        }

遇到的问题:

后台设置cookie但是通过js无法获取相应的cookie的值,why?

不知道。但是自己在一般处理程序中写的cookie却可以通过js获得。why?

 HttpCookie cookie = new HttpCookie("LoginName", HttpUtility.UrlEncode(username)); //定义cookie对象以及名为DocUrl的项 
        DateTime dt = DateTime.Now;                  //定义时间对象 
        TimeSpan ts = new TimeSpan(0, 12, 20, 0);         //天,小时,分钟,秒  ,cookie有效作用时间
        cookie.Expires = dt.Add(ts);                 //添加作用时间 
        context.Response.AppendCookie(cookie);               //确定写入cookie中

解决:

因为CookieHelper中设置了cookie的HttpOnly为true。

ASP.Net中HttpCookie对象的HttpOnly 属性 指定一个Cookie 是否可通过客户端脚本访问。不能通过客户端脚本访问为 true;否则为 false。默认值为 false。此属性并不能完全阻止客户端在本地获取cookies,但是可以增加通过脚本直接获取的难度。

posted @ 2019-01-10 22:37  黄树强  阅读(937)  评论(0编辑  收藏  举报