While this is possible in C#: (User is a L2S class in this instance)
User user = // function to get user
Session["User"] = user;
why this is not possible?
User user = // function to get user
HttpCookie cookie = new HttpCookie();
cookie.Value = user;
and how can it be done? I don't want to store the id of the user within the cookie and then do some validation.
Btw, if possible, is it secure to store an object within a cookie rather than only the ID ?
Store objects in the CookiesThe cookies store information in the string format only. If users want to store any other types of data in the cookies, they need to convert it to the string using the stringify() method. In this section, we will convert the object to a string and store it in cookies.
Store cookies in layers The last thing you want is for your cookies to stick together! To prevent sticking when you store your cookies, arrange them in a single layer and add a piece of parchment paper or waxed paper between layers. (Here's why you should bake cookies on parchment paper, too!)
The idea is to keep a JavaScript object (a hash array) of all little variable things you want to store in a cookie. Then, once ready, you encode the object into a JSON string and save it to a cookie. To load the data from a previously saved cookie, you decode the JSON string back into an object.
Cookies can only store string values. You cannot store an array directly into a cookie.
A cookie is just string data; the only way to do that would be to serialize it as a string (xml, json, base-64 of arbitrary binary, whatever), however, you shouldn't really trust anything in a cookie if it relates to security information ("who am I?") as a: it is easy for the end-user to change it, and b: you don't want the overhead of anything biggish on every single request.
IMO, caching this as the server is the correct thing; don't put this in a cookie.
You can use JSON
string myObjectJson = new JavaScriptSerializer().Serialize(myObject);
var cookie = new HttpCookie("myObjectKey", myObjectJson)
{
Expires = DateTime.Now.AddYears(1)
};
HttpContext.Response.Cookies.Add(cookie);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With