码迷,mamicode.com
首页 > 其他好文 > 详细

在Cookie中存储对象

时间:2015-07-21 01:35:50      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:cookie存储对象   cookie   json   urlencode   urldecode   

背景介绍


做项目过程中,用户登陆之后,需要将用户的信息存到Cookie中,但因为Cookie中只能存储字符串,所以想到了先把用户实体序列化成Json串,存储在Cookie中,用到的时候再拿出来反序列化。

道理很简单,网上的例子也很多,但还是遇到一些小困难。下面与大家分享成果。(我的开发环境为VS2012,.net framework版本为4.0,)

C#中Json与对象之间的互相转换


下载并引用Newtonsoft.Json.dll

定义一个简单的用户实体:

public class UserInfo
{
    /// <summary>
    /// 用户名称
    /// </summary>
    public string UserName { get; set; }
    /// <summary>
    /// 用户密码
    /// </summary>
    public string UserPwd { get; set; }
    /// <summary>
    /// 用户级别
    /// </summary>
    public string UserLevel { get; set; }
}

将对象序列化成Json串:

 /// <summary>
 /// 将对象序列化成Json
 /// </summary>
 /// <param name="obj">需要序列化的对象</param>
 /// <returns>序列化后的字符串</returns>
 public static string ObjectToJson(object obj)
 {
     return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
 }

将Json串反序列化成对象:

/// <summary>
/// 从Json字符串反序列化为对象
/// </summary>
/// <param name="jsonString">Json字符串</param>
/// <param name="obj">要生成的对象类型</param>
/// <returns>反序列化后的对象</returns>
public static object JsonToObject(string jsonString)
{
    return Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfo>(jsonString);
}

Cookie的使用


将实体序列化为Json并存入Cookie中:

//获取UserInfo对象
UserInfo enUser=new UserInfo()
{
    UserName="Danny",
    UserPwd="123456",
    UserLevel="admin"
}

//创建Cookie对象
HttpCookie userInfo = new HttpCookie("userInfo");

//将序列化之后的Json串以UTF-8编码,再存入Cookie
userInfo.Value = HttpUtility.UrlEncode(ObjectToJson(enUser), Encoding.GetEncoding("UTF-8"));  

//将cookie写入到客户端
System.Web.HttpContext.Current.Response.SetCookie(userInfo);

//设置cookie保存时间
userInfo.Expires = DateTime.Now.AddMinutes(20);

从Cookie中读取出Json串并反序列化成实体

//取出Cookie对象
HttpCookie userInfoCookie = System.Web.HttpContext.Current.Request.Cookies.Get("userInfo");

//从Cookie对象中取出Json串
string strUserInfo = HttpUtility.UrlDecode(userInfoCookie.Value, Encoding.GetEncoding("UTF-8"));

//Json串反序列化为实体
UserInfoViewModel userInfo = JsonToObject(strUserInfo) as UserInfoViewModel;

说明:实体的属性值有中文时,序列化的字符串存储到Cookie中时会产生乱码,为了防止产生乱码,我们在存入Cookie之前先用UrlEncode()和UrlDecode()对Json串进行编码与解码。
而且,一般的浏览器支持的Cookie存储的容量为4k(差也就差一两个字节),足够存储一个经过序列化的对象了。

版权声明:本文为博主原创文章,未经博主允许不得转载。

在Cookie中存储对象

标签:cookie存储对象   cookie   json   urlencode   urldecode   

原文地址:http://blog.csdn.net/huyuyang6688/article/details/46955119

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!