cool hit counter Storing objects in cookies_Intefrankly

Storing objects in cookies


Copyright: This is an original post by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/huyuyang6688/article/details/46955119

Background


In the process of doing the project, after the user logs in, the user's information needs to be stored in a cookie, but because cookies can only store strings, so the idea is to first serialize the user entity into a Json string and store it in the cookie, and then take it out and deserialize it when it is used.

The reasoning is simple and there are plenty of examples online, but there are still some minor difficulties. The results are shared with you below. (My development environment is VS2012, .net framework version 4.0,)

Interconversion between Json and objects in C#


Download and citeNewtonsoft.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; }
}

Serialization of objects into Json strings.

 /// <summary>
  /// Serialize objects to 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);
 }

Deserializing Json strings into objects.

/// <summary>
 /// Deserialize from a Json string to an object
/// </summary>
/// <param name="jsonString">Json string (computer science)</param>
/// <param name="obj"> The type of object to be generated</param>
/// <returns> The object after deserialization</returns>
public static object JsonToObject(string jsonString)
{
    return Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfo>(jsonString);
}

Use of Cookies


Serialization of entities to Json and storage in cookies.

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

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

 // encode the Json string after serialization in UTF-8 and then store it in the cookie
userInfo.Value = HttpUtility.UrlEncode(ObjectToJson(enUser), Encoding.GetEncoding("UTF-8"));  

 // Writing cookies to the client
System.Web.HttpContext.Current.Response.SetCookie(userInfo);

 // Set cookie retention time
userInfo.Expires = DateTime.Now.AddMinutes(20);

Read the Json string from the cookie and deserialize it into an entity

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

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

 //Json string deserialization to entities
UserInfoViewModel userInfo = JsonToObject(strUserInfo) as UserInfoViewModel;

Note: When the value of the entity's property has Chinese, the serialized string will be garbled when stored in the cookie. To prevent garbling, we use UrlEncode() and UrlDecode() to encode and decode the Json string before storing it in the cookie. Also, the average browser supports a cookie storage capacity of 4k (just shy of a byte or two), which is enough to store a serialized object.


Recommended>>
1、Common Blockchain Terms Explained
2、Programming is problem solving
3、Blockchain technology helps revolutionize global healthcare systems
4、Zerobased AI Elon Musk Another dream beyond SpaceX
5、Episode 46 What is the proofofinterest mechanism

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号