请参阅 How to store other languages (unicode) in cookies and get it back again、Unicode Cookie Value、How to send non-English unicode string using HTTP header? 和 Allowed characters in cookies,了解为什么需要对 cookie 值进行编码。
简而言之:大多数浏览器(但不是全部)都支持标头(发送 cookie)中的 Unicode 字符。一些浏览器将 Unicode 字节解释为 ASCII,从而产生Mojibake。
根据一些链接的问题,jQuery 似乎也发挥了作用,但我无法重现。
因此,要在所有浏览器中安全地存储 Unicode 字符(或者更确切地说是任何非 ASCII 或控制字符),您需要对字符进行编码。这可以通过例如 base64 和百分比编码来实现。
后者的一个实现,稍微改编自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]);
}
}
用法:
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);
请注意HttpUtility.UrlDecode()是危险的,使用AntiXSS来防止cookie值的跨站脚本和SQL注入,可以由客户端任意设置。
您或许还可以重新考虑在 cookie 中存储 Unicode 值。您可以通过其他方式轻松识别语言,例如通过代码 en-US 或其数据库索引(如果适用)。