Exception calling Add. Part of cookie is invalid
Asked Answered
L

2

13

I am using the Add method of System.Net.CookieContainer. It has worked well over the years but suddenly I am getting:

Exception calling "Add" with "2" argument(s): "The 'Value'='321,386,%2F%3Fa%3D1,http%3A%2F%2Fwww.xxxx.com%2Fpremium%2Fmoney' part of the cookie is invalid."

I was adding a cookie returned from a web page. The raw header from the web page is:

...
_chartbeat_uuniq=1;
_chartbeat5=321,386,%2F%3Fa%3D1,http%3A%2F%2Fwww.xxx.com%2Fpremium%2Fmoney;
gs_p_GSN-375009-Z=0;
...

What is wrong with the cookie value? Is it the comma?

Legitimacy answered 12/12, 2013 at 2:21 Comment(0)
P
12

You should encode the cookie value. The .NET method is UrlEncode in the System.Web.HttpUtility API. In .NET Framework, this UrlEncode method was provided by the System.Web.HttpServerUtility API. See also this SO answer.

Persecution answered 12/12, 2013 at 2:23 Comment(3)
I was thinking of that, but the cookie value already looks Url encoded.Legitimacy
maybe you should UrlDecode what you have and then encode it againPersecution
I turned on Fiddler2 and find that IE and Chrome are quite happy with the comma. It is only the CookieContainer class that balks.Legitimacy
R
0

According to Microsoft documentation

The value parameter for a Cookie must not be a null reference (Nothing in Visual Basic). The semicolon (";") and comma (",") characters are reserved and cannot be passed in the value parameter unless the string passed in the value parameter is enclosed in double quotes.

Following code will throw exception.

System.Net.Cookie cookie = new System.Net.Cookie("contoso", "123,456", "", "contoso.com");
new CookieContainer().Add(cookie);

However, if you add double quotes \" to the beginning and end of the value, the code will pass.

System.Net.Cookie cookie = new System.Net.Cookie("contoso", "\"123,456\"", "", "contoso.com");
new CookieContainer().Add(cookie);
Roentgenology answered 15/8, 2023 at 1:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.