Broken string in cookie after ampersand (javascript)

后端 未结 1 599
无人及你
无人及你 2020-12-21 17:20

I have a slight problem in that the string I\'m reading from a cookie is broken after the ampersand. So for example the string \"hello & world\" would just display \"hel

相关标签:
1条回答
  • 2020-12-21 17:50

    I think I have run into a similar problem in an ASP.NET MVC app.

    When I save a string containing ampersands to a cookie name/value pair it actually gets split into a series of name/value pairs

    e.g. attempting to save ("value","cookiedata123&book=2&page=0") will result in 3 name value pairs being created "value"="cookiedata123"; "book"="2"; and "page"="0".

    I have resolved this by URL Encoding the value just before writing to the cookie and URL Decoding it as soon as I read it out. In .net the calls look like this:

    // Encode
    return System.Web.HttpUtility.UrlEncode(cookieData);
    
    // Decode
    return System.Web.HttpUtility.UrlDecode(encodedCookieData);
    

    That takes care of any ampersands, equals signs etc that can cause problems. See this post here for info on characters that are allowed in cookies. Allowed characters in cookies

    0 讨论(0)
提交回复
热议问题