Storage Object of Cookie in C

  • 2021-07-10 20:36:28
  • OfStack

This article gives you a detailed explanation through the code, and the specific contents are as follows:

In the process of doing the project, after the user logs in, he needs to store the user's information in Cookie. However, because only strings can be stored in Cookie, he thought of serializing the user entity into Json strings first, storing them in Cookie, and then taking them out for deserialization when using them.

The reason is very simple, and there are many examples on the Internet, but there are still some minor difficulties. Let's share the results with you. (My development environment is VS 2012. net framework version 4.0.)

Conversion between Json and Object in C #

Download and reference Newtonsoft. Json. dll

Define a simple user entity:


public class UserInfo
{
 /// <summary>
 ///  User name 
 /// </summary>
 public string UserName { get; set; }
 /// <summary>
 ///  User password 
 /// </summary>
 public string UserPwd { get; set; }
 /// <summary>
 ///  User level 
 /// </summary>
 public string UserLevel { get; set; }
}


Serializes an object into an Json string:


 /// <summary>
 ///  Serializes an object into a Json
 /// </summary>
 /// <param name="obj"> Objects to be serialized </param>
 /// <returns> Serialized string </returns>
 public static string ObjectToJson(object obj)
 {
 return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
 }


To deserialize an Json string into an object:


/// <summary>
///  From Json String deserialization to object 
/// </summary>
/// <param name="jsonString">Json String </param>
/// <param name="obj"> Type of object to generate </param>
/// <returns> Deserialized object </returns>
public static object JsonToObject(string jsonString)
{
 return Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfo>(jsonString);
}


Use of Cookie

Serialize the entity into an Json and store it in an Cookie:

//Get an UserInfo object


UserInfo enUser=new UserInfo()
{
 UserName="Danny",
 UserPwd="123456",
 UserLevel="admin"
}

//Create an Cookie object
HttpCookie userInfo = new HttpCookie("userInfo");

//The serialized Json string is encoded with UTF-8 and stored in Cookie
userInfo.Value = HttpUtility.UrlEncode(ObjectToJson(enUser), Encoding.GetEncoding("UTF-8"));

//Write cookie to the client
System.Web.HttpContext.Current.Response.SetCookie(userInfo);

//Set cookie Save Time
userInfo.Expires = DateTime.Now.AddMinutes(20);
Read Json string from Cookie and deserialize it into entity

//Fetch the Cookie object
HttpCookie userInfoCookie = System.Web.HttpContext.Current.Request.Cookies.Get("userInfo");

//Fetch an Json string from an Cookie object
string strUserInfo = HttpUtility.UrlDecode(userInfoCookie.Value, Encoding.GetEncoding("UTF-8"));

//Json string deserialization into entity
UserInfoViewModel userInfo = JsonToObject(strUserInfo) as UserInfoViewModel;
Attribute value of the entity has Chinese, serialized string stored in Cookie will produce garbled code, in order to prevent the production of garbled code, we stored in Cookie before the first UrlEncode () and UrlDecode () Json string encoding and decoding.

Moreover, the Cookie storage capacity supported by a 1-like browser is 4k (which is one or two bytes short), which is enough to store one serialized object.

This article ends here, I hope you like it.


Related articles: