I am learning ASP.net using C# and I would like to know if we can store data other than strings, in cookies, like date/time or decimal or double.
Data of any type you can serialize into a string
and deserialize back into that type can be stored in a cookie. For instance: Object
, DateTime
, Int
, Decimal
, etc.
It entirely depends on your coding logic; string can be converted back to anything almost,
Is possible to get the object from cookie?
No, not directly as you are trying to. Don't think in terms of ASP.NET. Think in terms of what an HTTP cookie is in reality. It is an HTTP header. HTTP headers are only plain string values. The notion of object doesn't exist in the HTTP protocol.
So you will need to serialize the .NET object that you have into a string and then deserialize it back.
There are different serializers in .NET that you could use. For example use the BinaryFormatter and then Base64 encode the resulting byte array to store into the cookie.
The deserialization is the inverse process - you read the value from the cookie (which is always a string), then you Base64 decode it into a byte array which you deserialize back to the original object using the BinaryFormatter
.
Bear in mind though that the size of the cookies is limited and would vary between the different browsers. So don't expect to put large objects into cookies. The value will be stripped and you would get corrupt data. I wouldn't use them if the total serialized value of the object is larger than 2k characters.
Let's exemplify the process described earlier:
public class cookieTest
{
testC test;
public cookieTest()
{
test = new testC();
}
public testC GetTestC
{
get
{
var cookie = HttpContext.Current.Request.Cookies["test"];
return Deserialize<testC>(cookie.Value);
}
set
{
var cookie = new HttpCookie("test");
cookie.Expires = DateTime.Now.AddHours(8);
cookie["first"] = Serialize(value);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
}
private static string Serialize<T>(T instance)
{
using (var stream = new MemoryStream())
{
var serializer = new BinaryFormatter();
serializer.Serialize(stream, instance);
return Convert.ToBase64String(stream.ToArray());
}
}
private static T Deserialize<T>(string value)
{
using (var stream = new MemoryStream(Convert.FromBase64String(value)))
{
var serializer = new BinaryFormatter();
return (T)serializer.Deserialize(stream);
}
}
}
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