1.创建一个新的cookie,并赋值。
HttpCookie cookie;
cookie=new HttpCookie("user");
cookie.Domain = AppConfig.DomainName;
cookie.Values.Add("Username",username);
cookie.Values.Add("ldapStr",FindUserlist.Table.Rows[0]["ldapStr"].ToString());
Response.AppendCookie(cookie);
2.获取cookie的值
HttpCookie cookie=Request.Cookies["user"];
if(cookie!=null)
{
string username = cookie["Username"];
string ldapStr = cookie["ldapStr"];
}
3、写Cookie 值
HttpCookie myCookie = new HttpCookie("CookieName");
myCookie.Values.Add("CookieItem1","CookieItem1Value");
myCookie.Values.Add("CookieItem2","CookieItem2Value");
myCookie.Expires = DateTime.Now.AddDays(30);
Response.AppendCookie(myCookie);
4、清除Cookie值HttpCookie myCookie = HttpContext.Current.Response.Cookies["CookieObjectName"];
if(myCookie != null)
myCookie.Expires = DateTime.Now;
在做项目过程中,用户登陆之后,需要将用户的信息存到Cookie中,但因为Cookie中只能存储字符串,所以想到了先把用户实体序列化成Json串,存储在Cookie中,用到的时候再拿出来反序列化。
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;