How to Store and Retrieve an Object from Cookie in ASP.NET C#


Hi,

The name of the article suggests a typical problem which the developers come around whenever they are designing a login Form or want to store some useful object in the Cookie.

Unfortunately, cookies are unsecured and they can store string value only. So, to come out of this problem one need to understand that all data can not be / must not be saved in the Cookie. Some basic information like Login Name, user name, email can be saved but not password. Also, the developer need to make sure that no one can read the information except the website for which it is designed.

Solution?

1. First you need to prepare the object: How? – This can be done by serializing the object as a string. XML, JSON, base-64 of arbitrary binary etc.

2. Now, once your object is prepared, you need to add some security. In other word you need to encrypt the string such a way that the content can be readable by you only.

3. Last step: very easy, store the encrypted content as a string in the Cookie.

How to retrieve?

Just do the opposite.

1. Get the content of the cookie as a string

2. Decrypt the string

3. Deserialize it

4. Use the object as you like.

Now, lets see an example code.

here is the class whose object I want to store in my Cookie:

public class clsAdmin
{
private string _name;

public string Name
{
get { return _name; }

set { _name = value; }
}

private int _id;

public int AdminId
{
get { return _id; }
set { _id = value; }
}
}

Now, to serialize the object we can use the following code:

clsAdmin admin = new clsAdmin();

admin.Name = “UBK”;

admin.AdminId = 1;

//  Serialize it

String _serAdmin = SerializeAnObject(admin);

So, you have your serialized string. Now, you need to encrypt it. For this you can refer to this article or use your own code.

String _encVal = EncDec.Encrypt(_serAdmin, “YOUR PASSWORD”);

This time your data is ready to be saved in a cookie.

try
{
HttpCookie myCookie = new HttpCookie(“admin_cookie”);
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = _encVal;

// Set the cookie expiration date.
myCookie.Expires = now.AddDays(14);

// Add the cookie.
Response.Cookies.Add(myCookie);
}
catch (Exception _e)
{
//Failed to add Cookie
throw _e;
}

Once your Cookie is added, this is time to use it in our code.

try
{
HttpCookie myCookie = new HttpCookie(“admin_cookie”);
myCookie = Request.Cookies[“admin_cookie”];

// Read the cookie information and display it.
if (myCookie != null)
{
string _admStr = EncDec.Decrypt(myCookie.Value, “YOUR PASSWORD”);
clsAdmin _adm = DeSerializeAnObject(_admStr, typeof(clsAdmin)) as clsAdmin;

if (null != _adm && _adm.Login.Length > 0)
{
//DO Whatever you want with the object
}
}
else
Response.Write(“not found”);
}
catch (Exception _e)
{
//Failed to read cookie?
throw _e;
}

For XML Serializer I have used the wonderful code from http://weblogs.asp.net/stevewellens/archive/2009/07/02/serializing-and-deserializing-objects-to-and-from-xml.aspx

/// ---- SerializeAnObject -----------------------------
/// <summary>
/// Serializes an object to an XML string
/// </summary>
///AnObject">The Object to serialize
/// <returns>XML string</returns>

public static string SerializeAnObject(object AnObject)
{
    XmlSerializer Xml_Serializer = new XmlSerializer(AnObject.GetType());
    StringWriter Writer = new StringWriter();      

    Xml_Serializer.Serialize(Writer, AnObject);
    return Writer.ToString();
}
 

/// ---- DeSerializeAnObject ------------------------------
/// <summary>
/// DeSerialize an object
/// </summary>
///XmlOfAnObject">The XML string
///ObjectType">The type of object
/// A deserialized object...must be cast to correct type

public static Object DeSerializeAnObject(string XmlOfAnObject, Type ObjectType)
{       
    StringReader StrReader = new StringReader(XmlOfAnObject);
    XmlSerializer Xml_Serializer = new XmlSerializer(ObjectType);
    XmlTextReader XmlReader = new XmlTextReader(StrReader);
    try
    {
        Object AnObject = Xml_Serializer.Deserialize(XmlReader);
        return AnObject;
    }
    finally
    {
        XmlReader.Close();
        StrReader.Close();
    }
}

Hope this will help someones quest :)