zoukankan      html  css  js  c++  java
  • CookieHelper cookie操作

    public class CookieHelper
        {
            public static void AddCookie(object obj, string cookieName)
            {
                BinaryFormatter bf = new BinaryFormatter();  //声明一个序列化类
                MemoryStream ms = new MemoryStream();  //声明一个内存流
                bf.Serialize(ms, obj);  //执行序列化操作
                byte[] result = new byte[ms.Length];
                result = ms.ToArray();
                string temp = System.Convert.ToBase64String(result);
                /*此处为关键步骤,将得到的字节数组按照一定的编码格式转换为字符串,不然当对象包含中文时,进行反序列化操作时会产生编码错误*/
                ms.Flush();
                ms.Close();
                //string temp = XmlUtil.Serializer(obj.GetType(), obj);
                HttpCookie cookie = new HttpCookie(cookieName);  //声明一个Key为Obj的Cookie对象
                cookie.Expires = DateTime.Now.AddDays(1.0);  //设置Cookie的有效期到明天为止,此处时间可以根据需要设置
                cookie.Value = temp;  //将cookie的Value值设置为temp
                System.Web.HttpContext curContext = System.Web.HttpContext.Current;
                curContext.Response.Cookies.Add(cookie);
            }
    
            public static Object ReadCookie(string cookieName)
            {
                try
                {
                    System.Web.HttpContext curContext = System.Web.HttpContext.Current;
                    string result = curContext.Request.Cookies[cookieName].Value;
                    //return (XmlUtil.Deserialize(typeof(UserInfo), result));
                    byte[] b = System.Convert.FromBase64String(result);  //将得到的字符串根据相同的编码格式分成字节数组
                    MemoryStream ms = new MemoryStream(b, 0, b.Length);  //从字节数组中得到内存流
                    BinaryFormatter bf = new BinaryFormatter();
                    return bf.Deserialize(ms);
                }
                catch
                {
                    return null;
                }
            }
            public static void DeleteCookie(string cookieName)
            {
                try
                {
                    System.Web.HttpContext curContext = System.Web.HttpContext.Current;
                    //HttpCookie mycookie;
                    //mycookie = curContext.Request.Cookies[cookieName]; 
                    //TimeSpan ts = new TimeSpan(0, 0, 0, 0);//时间跨度             
                    //mycookie.Expires = DateTime.Now.Add(ts);//立即过期            
                    curContext.Response.Cookies.Remove(cookieName);//清除        
                }
                catch
                {
                   
                }
            }
    
        }
  • 相关阅读:
    weblogic的ssrf漏洞
    web服务器、Web中间件和Web容器的区别
    linux C判断文件是否存在
    Linux 文件锁flock 实现两个进程相互监听存活状态
    Linux 进程间通信之管道(pipe),(fifo)
    Linux 进程间通信系列之 信号
    android Binder机制(一)架构设计
    Linux 系统 文件锁 fcntl函数详解
    execlp启动android进程命令
    Linux环境编程--waitpid与fork与execlp
  • 原文地址:https://www.cnblogs.com/ypyhy/p/6677365.html
Copyright © 2011-2022 走看看