Cookie操作类

public class Cookie
    {
        //添加Cookie
        public static void AddCookie(string cookieName,string value,DateTime expireDays)
        {
            string domain = GetDomain();
            HttpCookie authCookie = new HttpCookie(cookieName, value);
            authCookie.Path = "/";
            authCookie.Domain = domain;
            authCookie.Expires = expireDays;
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }
        //获取Cookie
        public static string GetCookie(string cookieName)
        {
            string value = "";
            if (HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                value = HttpContext.Current.Request.Cookies[cookieName].Value.ToString();
            }
            return value;
        }
        //设置cookie
        public static void SetCookie(string cookieName,string value)
        {
            if (HttpContext.Current.Request.Cookies[cookieName] == null)
            {
                AddCookie(cookieName, value, DateTime.Now.AddYears(50));
            }
            else
            {
                RemoveCookie(cookieName);
                AddCookie(cookieName, value, DateTime.Now.AddYears(50));
            }
        }
        //读取域名
        
        private static string GetDomain()
        {
            string defaultdomain = TB.Trade.Config.GetDomain()+".com";
            try
            {
                Uri host = HttpContext.Current.Request.Url;
                if (host.HostNameType == UriHostNameType.Dns)
                {
                    string domain = host.Host;

                    string[] domainsplit = domain.Split(new char[] { '.' });
                    int domainlength = domainsplit.Length;
                    if (domainlength > 1)
                    {
                        return domainsplit[domainlength - 2] + "." + domainsplit[domainlength - 1];
                    }
                    else
                    {
                        return domain;
                    }
                }
                else
                {
                    return host.Host;
                }
            }
            catch
            {
                return defaultdomain;
            }
        }
        //删除
        public static void RemoveCookie(string cookieName)
        {
            if (HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.Now.AddYears(-100); 
            }
        }

posted on 2014-07-21 14:44  忙碌ing  阅读(175)  评论(0)    收藏  举报

导航