Storing a byte array in a Cookie (nom!) C# MVC
It seems that cookies can eat store just about any kind of data, but keeping to a limit of 20 cookies per domain and 4096 bytes per cookie is the safe way to do it (source).
I needed to store a byte array in a cookie (encrypted data) and Brian Pedersen’s article on streaming objects into cookies helped me to come up with the solution.
The original C# code I came up with did not work
// Write cookie HttpCookie cookie = new HttpCookie("myCookie"); cookie.Value = System.Text.Encoding.UTF8.GetString(myByteArray); Response.Cookies.Add(cookie); // Read cookie HttpCookie c = Request.Cookies["myCookie"]; byte[] retrievedByteArray = System.Text.Encoding.UTF8.GetBytes(c.Value);
For some reason what I got back was not the same as what I put in (more bytes!).
However using Convert, like Brian, did work
// Write cookie HttpCookie cookie = new HttpCookie("myCookie"); cookie.Value = Convert.ToBase64String(myByteArray); Response.Cookies.Add(cookie); // Read cookie HttpCookie c = Request.Cookies["myCookie"]; byte[] retrievedByteArray = Convert.FromBase64String(c.Value);
Note
The above code will work in a Controller, to do the same thing elsewhere (e.g. within a class) use HttpContext.Current.Response.Cookies and HttpContext.Current.Request.Cookies.
For example:
HttpContext.Current.Response.Cookies.Add(cookie);
For more information on storing objects in cookies please see Brian Pedersen’s blog post.