0
httpwebresponse not getting cookies

Solved 1 Answers 30 Views Programming
0 1
I am using c#.net to send POST request and receive response. I've setup CookingContainer in my request. But when I try to receive cookies in response, its null. How do I set it up?

1 Answer

0
Best answer
0

First: We need to initiate cookie collector with Request.

httpRequest.CookieContainer = new CookieContainer();

Second: In case cookie collector is corrupted, we need to manually fix it.

CookieCollection cookiesCollections = response.Cookies;
            if(cookiesCollections == null)
            {
                {
                    for (int i = 0; i < response.Headers.Count; i++)
                    {
                        string name = response.Headers.GetKey(i);
                        if (name != "Set-Cookie")
                            continue;
                        string value = response.Headers.Get(i);
                        foreach (var singleCookie in value.Split(','))
                        {
                            Match match = Regex.Match(singleCookie, "(.+?)=(.+?);");
                            if (match.Captures.Count == 0)
                                continue;
                            response.Cookies.Add(
                                new Cookie(
                                    match.Groups[1].ToString(),
                                    match.Groups[2].ToString(),
                                    "/",
                                    httpRequest.Host.Split(':')[0]));
                        }
                    }
                }

answered by (151 points)
selected by

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
...