在Cookie中儲存物件,Cookie儲存物件

來源:互聯網
上載者:User

在Cookie中儲存物件,Cookie儲存物件
背景介紹

做項目過程中,使用者登陸之後,需要將使用者的資訊存到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編碼,再存入CookieuserInfo.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(差也就差一兩個位元組),足夠儲存一個經過序列化的對象了。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.