1

My C# Windows Forms program needs to talk to servers that include multiple Set-Cookie headers in HTTP responses.

.NET's HttpWebResponse seems to concatenate the contents of multiple Set-Cookie headers into one value - leaving the final value invalid. This results in sent cookies not being stored properly when using an associated CookieContainer.

Example

HttpWebRequest initiates a request and server replies with...

HTTP/1.1 200 OK
....
Set-Cookie: cookie1=123; Domain=127.0.0.1; Path=/; Expires=Wed, 13 Jan 2021 22:23:01 GMT
Set-Cookie: cookie2=456; Domain=127.0.0.1; Path=/somepath; Expires=Wed, 13 Jan 2021 22:23:01 GMT
....

...and HttpWebResponse's header value (copied from VS Debugger) is:

Set-Cookie: cookie1=123; Domain=127.0.0.1; Path=/; Expires=Wed, 13 Jan 2021 22:23:01 GMT,cookie2=456; Domain=127.0.0.1; Path=/somepath; Expires=Wed, 13 Jan 2021 22:23:01 GMT

HttpWebResponse only contains cookie1 in Cookies property.

.NET Reflection on the original HttpWebRequest's CookieContainer to get all cookies (https://stackoverflow.com/a/15991071) also shows only cookie1 is parsed into an object and cookie2 is ignored.

Are there ways to get multiple Set-Cookie headers handled properly without resorting to (significantly) lower-level or more complicated alternatives to HttpWebResponse?

Community
  • 1
  • 1
user1092719
  • 483
  • 1
  • 5
  • 17
  • Hello there, have you solved it? Because I'm interested in this problem. – czubehead Jul 01 '15 at 19:11
  • Technically, no. I found out that the problem was with the server, not the client. The server was a quick C# WinForms application which I wrote for testing purposes, and in that I was doing `ctx.Response.Headers.Add("Set-Cookie: ....");` multiple times. The server combined these into one `Set-Cookie` header. As the server was for quick testing purposes only, the bug in `HttpWebResponse` wasn't much of a problem for me in the long run, but unfortunately the problem isn't really solved. – user1092719 Jul 03 '15 at 14:28

1 Answers1

0

You didn't specify any code samples you have problems with. However i had similar problems with CookieContainer.SetCookies() method. When i tried to set a nice CookieHeader:

u=21seag24.ctcggq.f54cfsvgqp; v=1466603692; auth=1; dfp_group=15

CookieContainer absorbed only 1st cookie and thats it. But i need them All.!

To deal with this problem i added extra method:

    public void FillCookieContainer(string cookieString, string url)
    {
        foreach (var cookieElement in cookieString.Split(';'))
        {
            CookieContainer.SetCookies(new Uri(url), cookieElement.Trim());
        }
    }

Referring to Microsoft documentation CookieContainer have a specific method like CookieCutter and CookieParser class. In general it rejects all the cookies with wrong format (not RFC2109/RFC2965).

Trinitron
  • 374
  • 3
  • 12