c# - 如何在 cookie 中安全地存储 Unicode 字符?

标签 c# jquery asp.net-mvc cookies

我正在使用 cookie 在搜索页面中显示一些数据,但我的 cookie 在使用 Unicode 字符时会混淆值。例如,当我存储 Inglês 时,当我读回它时,我得到的是 Inglês

这是我保存 cookie 的方式:

public void SalvaValue(string sessionKey, string sessionValue)
{
    Response.Cookies.Add(new HttpCookie(sessionKey));

    var httpCookie = Response.Cookies[sessionKey];

    if (httpCookie != null) httpCookie.Value = sessionValue;
    if (httpCookie != null) httpCookie.Expires = DateTime.Now.AddDays(14);
}

这是我检索它的方式:

if (Request.Cookies["BuscaTipo"] != null)
{
    tipoBusca = Request.Cookies["BuscaTipo"].Value.ToString();

     var cookie = new HttpCookie("BuscaTipo") { Expires = DateTime.Now.AddDays(-1) };
     Response.Cookies.Add(cookie);
}

当我调试站点时,它在代码中显示了正确的值,但在我使用 jQuery 执行请求后,该值出现了错误的字符。

如何在 cookie 中安全地存储 Unicode 字符?

最佳答案

参见 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 值进行编码。

简而言之:大多数浏览器都支持 header (其中发送 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防止跨站点脚本和 SQL 注入(inject)来自 cookie 值,可以由客户端任意设置。

您或许还可以重新考虑在 cookie 中存储 Unicode 值。您可以通过其他方式轻松识别语言,例如通过代码 en-US 或其数据库索引(如果适用)。

关于c# - 如何在 cookie 中安全地存储 Unicode 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28507778/

相关文章:

c# - 方法中动态方法返回值的显式转换不允许调用扩展方法

c# - 如何绑定(bind)到 View 中但不在 View 模型中的属性?

css - 为什么 Styles.Render 在大括号内不起作用?

asp.net-mvc - 使用 Knockout JS + MVC + 服务器端模型验证显示错误?

javascript - 当 ASP.NET MVC 5 应用程序中的表单有效时触发 jQuery 函数

c# - 如果发生异常,则退出函数/方法

C# 如何使用 .OrderBy 处理多列并将列号解码为列名?

jquery - JQuery 中的点和哈希符号是什么意思?

jquery - 创建一个按钮,当它被按住时从中心开始填充,如果它被第二次按住则恢复到原来的颜色

javascript - 单击图像显示/隐藏多个 div