Search code examples
c#asp.netcookiesmessage-passing

cookie can have data other than string


I have an object of a class MeetingList I want to pass this object through cookie it is giving me error while casting

Writing Cookie

HttpCookie cookies = new HttpCookie("QuickJumpCookie");
cookies["MeetingList"] = bal.GetMeetingList(personID, "Open").ToString();
Response.Cookies.Add(cookies);

Reading Cookie

HttpCookie cookies = Request.Cookies["QuickJumpCookie"];
MeetingList ml = (MeetingList) cookies["MeetingList"]; <-- Error in this line

Solution

  • I suppose you should serialize and then desirialize your MeetingList class

    Serialize your object in cookie in some format(for example in JSON) and then deserialize it. Personally i use this newtonsoft.com/json library. Your code will look like

    JsonConvert.SerializeObject(YourMeetingListObject) 

    and then

    MeetingList ml = (MeetingList) JsonConvert.DeserializeObject(cookies["MeetingList"])