I have this cod:
[Serializable]
public class testC
{
string sir;
public testC()
{
sir = string.Empty;
}
public string GetString
{
get { return sir; }
set { sir = value; }
}
}
public class cookieTest
{
testC test;
public cookieTest()
{
test = new testC();
}
public testC GetTestC
{
get
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["test"];
test = cookie["first"] as testC;
return test;
}
set
{
HttpCookie cookie = new HttpCookie("test");
cookie.Expires = DateTime.Now.AddHours(8);
cookie["first"] = value.ToString();
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
}
}
And i get this error
Cannot convert type ‘string’ to ‘testC’ via a reference conversion,
boxing conversion, unboxing conversion, wrapping conversion, or null
type conversion
Is possible to get the object from cookie? Or I must to write into cookie all my data to set and get all data and create a new object to get?
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: