SoFunction
Updated on 2025-03-06

Cookie storage object in C#

This article explains it in detail through code, the specific content is as follows:

During the project, after the user logs in, he needs to store the user's information in the cookie. However, because the cookie can only store strings, he thought of serializing the user entity into a Json string first, storing it in the cookie, and then deserializing it when used.

The reason is very simple, there are many examples on the Internet, but I still encounter some minor difficulties. Let’s share the results with you below. (My development environment is VS2012, the .net framework version is 4.0,)

Conversion between Json and object in C#

Download and quote

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; }
}


Serialize the object into a Json string:

 /// <summary>
 /// Serialize the object into Json /// </summary>
 /// <param name="obj">Objects that need to be serialized</param> /// <returns>Serialized string</returns> public static string ObjectToJson(object obj)
 {
 return (obj);
 }


Deserialize the Json string into an object:

/// &lt;summary&gt;
/// Deserialize from Json string to object/// &lt;/summary&gt;
/// <param name="jsonString">Json String</param>/// <param name="obj">Object type to generate</param>/// <returns>Deserialized object</returns>public static object JsonToObject(string jsonString)
{
 return &lt;UserInfo&gt;(jsonString);
}


Use of cookies

Serialize the entity into Json and store it in the cookie:

//Get UserInfo object

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

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

//Encode the serialized Json string in UTF-8 and then store it in the cookie
= (ObjectToJson(enUser), ("UTF-8")); 

//Write cookies to client
(userInfo);

//Set the cookie saving time
= (20);
Read out Json string from cookie and deserialize it into entity

//Take out the cookie object
HttpCookie userInfoCookie = ("userInfo");

//Fetch the Json string from the cookie object
string strUserInfo = (, ("UTF-8"));

//Json string deserializes to entity
UserInfoViewModel userInfo = JsonToObject(strUserInfo) as UserInfoViewModel;
Note: When the attribute value of an entity is in Chinese, the serialized string will produce garbled code when stored in the cookie. In order to prevent garbled code, we first use UrlEncode() and UrlDecode() to encode and decode the Json string before storing the cookie.

Moreover, the capacity of cookies supported by general browsers is 4k (the difference is only one or two bytes), which is enough to store a serialized object.

This article ends here, I hope you like it.