See How to save other languages (Unicode) in cookies and return them back , Unicode Cookie Value . How to send a non-English Unicode string using an HTTP header? and Allowed characters in cookies to explain why you need to encode cookie values.
In short: Unicode characters in the headers (in which cookies are sent) are supported by most browsers, but not all. Some browsers interpret Unicode bytes as ASCII, resulting in Mojibake .
jQuery also seems to play a role in accordance with some related questions, but I cannot reproduce this.
Therefore, to safely store Unicode characters (or rather, any non-ASCII or control characters) in all browsers, you need to encode characters. This can be implemented, for example, using base64 and percent encoding.
An implementation of the latter, slightly adapted from Cookies and Unicode characters :
public static class CookieExtensions { public static string DecodedValue(this HttpCookie cookie) { if (cookie == null) { throw new ArgumentNullException("cookie"); } return HttpUtility.UrlDecode(cookie.Value); } public static void SetEncodedValue(this HttpCookie cookie, string value) { if (cookie == null) { throw new ArgumentNullException("cookie"); } cookie.Value = HttpUtility.UrlEncode(value); } public static string DecodedValues(this HttpCookie cookie, string name) { if (cookie == null) { throw new ArgumentNullException("cookie"); } return HttpUtility.UrlDecode(cookie.Values[name]); } public static void SetEncodedValues(this HttpCookie cookie, string name, string value) { if (cookie == null) { throw new ArgumentNullException("cookie"); } cookie.Values[name] = HttpUtility.UrlEncode(value); } public static string DecodedValues(this HttpCookie cookie, int index) { if (cookie == null) { throw new ArgumentNullException("cookie"); } return HttpUtility.UrlDecode(cookie.Values[index]); } }
Using:
if (Request.Cookies["TestCookieValue"] != null) { ViewBag.CookieValue = Request.Cookies["TestCookieValue"].DecodedValue(); } if (Request.Cookies["TestCookieValues"] != null) { ViewBag.CookieValues = Request.Cookies["TestCookieValues"].DecodedValues("foo"); ViewBag.CookieValuesIndexed = Request.Cookies["TestCookieValues"].DecodedValues(0); } var cookieWithValue = new HttpCookie("TestCookieValue"); cookieWithValue.Expires = DateTime.Now.AddHours(1); cookieWithValue.SetEncodedValue("Inglês"); Response.SetCookie(cookieWithValue); var cookieWithValues = new HttpCookie("TestCookieValues"); cookieWithValues.Expires = DateTime.Now.AddHours(1); cookieWithValues.SetEncodedValues("foo", "Inglês"); Response.SetCookie(cookieWithValues);
Please note that HttpUtility.UrlDecode() is dangerous, use AntiXSS to prevent the use of Scripting scripts and SQL injections from cookie values that can be arbitrarily set by the client.
You might also want to reconsider storing Unicode values in cookies. You can easily identify the language otherwise, for example, through the en-US code or its database index, if applicable.