问题
Have found very interesting issue in asp.net with cookies: when adding cookie with value like test& using
HttpCookie cookie = new HttpCookie("test", "test&");
Response.Cookies.Add(cookie);
and then trying to retrieve value Request.Cookies["test"] trailing ampersand is lost. If it is not trailing it is not lost. In firebug or javascript data is correct so it is asp.net specific I think. Of course mostly could say just use UrlEncode. But is it really necessary? Is there any list of disallowed charters for cookies (because I think it is smaller than for URLs)? I have found similar topic but there is no & symbol in restricted list: Allowed characters in cookies
回答1:
The ampersand is not an allowed character in a cookie. It's necessary to encode the cookie data with the UrlEncode method.
System.Web.HttpUtility.UrlEncode(cookie);
See also these SO questions/answers:
- Broken string in cookie after ampersand (javascript)
- How do you use an Ampersand in an HTTPCookie in VB.NET?
来源:https://stackoverflow.com/questions/5621190/asp-net-and-cookies-special-characters