开发者论坛

 找回密码
 注册 (请使用非IE浏览器)
查看: 2828|回复: 0

再来一个,asp.net Cookie处理类

[复制链接]

0

精华

10

贡献

38

赞扬

实习版主

帖子
18
软币
158
在线时间
10 小时
注册时间
2013-9-30
发表于 2014-5-12 14:09:39 | 显示全部楼层 |阅读模式
[C#] 纯文本查看 复制代码
using System;
using System.Web;
using System.Web.Security;

namespace OIFrameWork.Common
{
    public class CookieFunction
    {
        private static CookieFunction _instance;
        public static readonly object CookieFunctionObj = new object();

        public static CookieFunction GetInstance()
        {
            if (_instance != null)
                return _instance;
            lock (CookieFunctionObj)
            {
                return _instance ?? ( _instance = new CookieFunction() );
            }
        }

        public bool InsertCookie(String userCode,String loginName, int outMinutes)
        {
            try
            {
                var ticket = new FormsAuthenticationTicket(1, userCode,
                    DateTime.Now, DateTime.Now.AddMinutes(outMinutes), true, loginName,
                    FormsAuthentication.FormsCookiePath);
                var key = FormsAuthentication.Encrypt(ticket);
                var hkCookie = new HttpCookie(FormsAuthentication.FormsCookieName, key)
                {
                    Domain = FormsAuthentication.CookieDomain
                };
                HttpContext.Current.Response.Cookies.Add(hkCookie);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 读取Cookies
        /// </summary>
        /// <param name="strName">主键</param>
        /// <returns></returns>
        public string GetCookie(string strName)
        {
            var cookie = HttpContext.Current.Request.Cookies[strName];
            return cookie != null ? cookie.Value : null;
        }

        /// <summary>
        /// 删除Cookies
        /// </summary>
        /// <param name="strName">主键</param>
        /// <returns></returns>
        public bool DelCookie(string strName)
        {
            try
            {
                var cookie = new HttpCookie(strName)
                {
                    Expires = DateTime.Now.AddDays(-1)
                };
                //Cookie.Domain = ".xxx.com";//当要跨域名访问的时候,给cookie指定域名即可,格式为.xxx.com
                HttpContext.Current.Response.Cookies.Add(cookie);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public void QuitCookie()
        {
            FormsAuthentication.SignOut();
        }
    }
}

评分

参与人数 3赞扬 +3 收起 理由
maple + 1 感谢分享
Cactus_CC + 1 很给力
seamone + 1 赞一个

查看全部评分

回复

使用道具 举报

Archiver|手机版|小黑屋|开发者网 ( 苏ICP备08004430号-2 )
版权所有:南京韵文教育信息咨询有限公司

GMT+8, 2024-4-27 00:24

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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