C#语法糖之Cookies操作类 asp.net

用法:

   //声名一个数据集合
            var listString = new List<string>() { "a", "b", "c" };
            //缓存key
            string key = "cokey";

            //获取实例
            var cookiesManager = CookiesManager<List<string>>.GetInstance();

            //插入缓存
            cookiesManager.Add(key, listString, cookiesManager.Minutes * 30);//过期30分钟
            //add有其它重载 上面是最基本的

            //获取
            List<string> cookiesList = cookiesManager[key];

            //其它方法
            cookiesManager.ContainsKey(key);

            cookiesManager.Remove(key);//删除

            cookiesManager.RemoveAll(c => c.Contains("sales_"));//删除key包含sales_的cookies

            cookiesManager.GetAllKey();//获取所有key

  

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace SyntacticSugar
{

    /// <summary>
    /// ** 描述:cookies操作类
    /// ** 创始时间:2015-6-9
    /// ** 修改时间:-
    /// ** 作者:sunkaixuan
    /// ** 使用说明:
    /// </summary>
    /// <typeparam name="V">值</typeparam>
    public class CookiesManager<V> : IHttpStorageObject<V>
    {

        #region 全局变量
        private static CookiesManager<V> _instance = null;
        private static readonly object _instanceLock = new object();
        #endregion

        /// <summary>
        /// 获取实例 (单例模式)
        /// </summary>
        /// <returns></returns>
        public static CookiesManager<V> GetInstance()
        {
            if (_instance == null)
                lock (_instanceLock)
                    if (_instance == null)
                        _instance = new CookiesManager<V>();
            return _instance;
        }

        /// <summary>
        /// 添加cookies ,注意value最大4K (默认1天)
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        public override void Add(string key, V value)
        {
            Add(key, value, Day);
        }
        /// <summary>
        /// 添加cookies ,注意value最大4K
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="cookiesDurationInSeconds">有效时间单位秒</param>
        public void Add(string key, V value, int cookiesDurationInSeconds)
        {
            HttpResponse response = HttpContext.Current.Response;
            if (response != null)
            {
                HttpCookie cookie = response.Cookies[key];
                if (cookie != null)
                {
                    if (typeof(V) == typeof(string))
                    {
                        string setValue = value.ToString();
                        Add(key, cookiesDurationInSeconds, cookie, setValue, response);
                    }
                    else
                    {
                        System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                        string setValue = jss.Serialize(value);
                        Add(key, cookiesDurationInSeconds, cookie, setValue, response);

                    }
                }
            }
        }

        private void Add(string key, int cookiesDurationInSeconds, HttpCookie cookie, string setValue, HttpResponse response)
        {
            if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
                cookie.Values.Set(key, setValue);
            else
                if (!string.IsNullOrEmpty(setValue))
                    cookie.Value = setValue;
            if (cookiesDurationInSeconds > 0)
                cookie.Expires = DateTime.Now.AddSeconds(cookiesDurationInSeconds);
            response.SetCookie(cookie);
        }

        public override bool ContainsKey(string key)
        {
            return Get(key) != null;
        }

        public override V Get(string key)
        {
            string value = string.Empty;
            if (context.Request.Cookies[key] != null)
                value = context.Request.Cookies[key].Value;
            if (typeof(V) == typeof(string))
            {
                return (V)Convert.ChangeType(value, typeof(V));
            }
            else
            {
                System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                return jss.Deserialize<V>(value);
            }
        }

        public override IEnumerable<string> GetAllKey()
        {
            var allKeyList = context.Request.Cookies.AllKeys.ToList();
            foreach (var key in allKeyList)
            {
                yield return key;
            }
        }

        public override void Remove(string key)
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request != null)
            {
                HttpCookie cookie = request.Cookies[key];
                cookie.Expires = DateTime.Now.AddDays(-1);
                if (cookie != null)
                {
                    if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
                        cookie.Values.Remove(key);
                    else
                        request.Cookies.Remove(key);
                }
            }
        }

        public override void RemoveAll()
        {
            foreach (var key in GetAllKey())
            {
                Remove(key);
            }
        }

        public override void RemoveAll(Func<string, bool> removeExpression)
        {
            var removeList = GetAllKey().Where(removeExpression).ToList();
            foreach (var key in removeList)
            {
                Remove(key);
            }
        }

        public override V this[string key]
        {
            get { return Get(key); }
        }
    }
}

  

using System;
namespace SyntacticSugar
{
    public abstract class IHttpStorageObject<V>
    {

        public int Minutes = 60;
        public int Hour = 60 * 60;
        public int Day = 60 * 60 * 24;
        public System.Web.HttpContext context = System.Web.HttpContext.Current;
        public abstract void Add(string key, V value);
        public abstract bool ContainsKey(string key);
        public abstract V Get(string key);
        public abstract global::System.Collections.Generic.IEnumerable<string> GetAllKey();
        public abstract void Remove(string key);
        public abstract void RemoveAll();
        public abstract void RemoveAll(Func<string, bool> removeExpression);
        public abstract V this[string key] { get; }
    }
}

  

时间: 2024-10-12 03:11:20

C#语法糖之Cookies操作类 asp.net的相关文章

C#语法糖之 cache操作类 asp.net

因为考虑到我下面我将写session cookies 等 操作类 ,与cache具有共性. 所以都统一继承了IHttpStorageObject  abstract class 来保函数风格的统一 ,但是又为了调用方便,抽象中又使用了单例来简化调用. 使用方法很简单: //声名一个数据集合 var listString = new List<string>() { "a", "b", "c" }; //缓存key string key

C#语法糖之 session操作类 asp.net

用法: //声名一个数据集合 var listString = new List<string>() { "a", "b", "c" }; //session key string key = "sekey"; //获取实例 var sessionManager = SessionManager<List<string>>.GetInstance(); //添加session session

Cookies操作类

实现代码: //声名一个数据集合 var listString = new List<string>() { "a", "b", "c" }; //缓存key string key = "cokey"; //获取实例 var cookiesManager = CookiesManager<List<string>>.GetInstance(); //插入缓存 cookiesManager.A

.NET常用工具类——COOKIES操作类

using System;using System.Collections;using System.Collections.Generic;using System.Collections.Specialized;using System.Text;using System.Web;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.We

Python语法糖系列

摘自:https://blog.csdn.net/five3/article/details/83474633语法糖说明语法糖(Syntactic sugar): 计算机语言中特殊的某种语法 这种语法对语言的功能并没有影响 对于程序员有更好的易用性 能够增加程序的可读性简而言之,语法糖就是程序语言中提供[奇技淫巧]的一种手段和方式而已. 通过这类方式编写出来的代码,即好看又好用,好似糖一般的语法.固美其名曰:语法糖 一个简单的例子假设:有2个数字,现需要从中得到最大的那个数字.如何实现? b =

ASP.net如何保证EF操作类线程内唯一

说到线程内唯一,肯定会想到单例模式,但是如果多用户访问网站就会出现问题.ASP.net中有两种方法可以保证EF操作类线程内唯一(目前只会这两种,以后有好的方法再添加): 1.httpcontext(实现原理也是通过数据槽callcontext) 将EF操作类通过键值对方法保存在HttpContext.Current.Items["key"],封装成方法直接调用 2.callcontext public static DbContext CreateDbContext() { DbCon

ASP.NET(C#) 数据库操作类 SqlServerDataBase

1 using System.Web.Security; 2 using System.Web.UI; 3 using System.Web.UI.WebControls; 4 using System.Web.UI.WebControls.WebParts; 5 using System.Web.UI.HtmlControls; 6 using System.Data.SqlClient; 7 8 namespace Mysqlserver 9 { 10 /// <summary> 11 /

asp.net文件操作类

/** 文件操作类 **/ #region 引用命名空间 using System; using System.Collections.Generic; using System.Text; using System.IO; #endregion namespace CommonUtilities { /// <summary> /// 文件操作类 /// </summary> public class FileHelper { #region 检测指定目录是否存在 /// <

C#4.0语法糖之第五篇: 匿名类 &amp; 匿名方法

今天时间有点早,所以上来在写一篇文章吧,继续上一篇的文章,在我们平时编程过程中有没有遇到过这样的一个情景,你定义的类只是用来封装一些相关的数据,但并不需要相关联的方法.事件和其他自定义的功能.同时,这个类仅仅在当前的应用程序中使用,而不需要在项目间重用.你所需要的只是一个“临时的”类型,现在我们来看看这个传统类的定义: 1 internal class oneClass 2  3 { 4  5      //定义若干私有数据成员 6  7      //通过属性来封装每个数据成员 8  9