Yauhen.F
Yauhen.F

Reputation: 2402

asp.net and cookies special characters

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

Upvotes: 4

Views: 4170

Answers (1)

Martin Buberl
Martin Buberl

Reputation: 47114

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:

Upvotes: 5

Related Questions