C# CookieContainer not storing cookies from request to response?

271 Views Asked by At

I'm sending a request but the cookies are not being stored in my container for the response?

Example of code -

        string uri = "https://www.localhost.com/"
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.ContentType = "application/x-www-form-urlencoded";
        CookieContainer cookies = new CookieContainer();
        request.CookieContainer = cookies;
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;


        using (Stream stream = request.GetRequestStream())
        {
            byte[] bytes = new UTF8Encoding().GetBytes(s);
            stream.Write(bytes, 0, bytes.Length);
        }


        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            using (Stream stream2 = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream2, Encoding.UTF8))
                    {
                        str6 = reader.ReadToEnd();
                    }
                }
        }

as you can see I've implemented

  CookieContainer cookies = new CookieContainer();
  request.CookieContainer = cookies;

Which should store the cookies from the request within the container for further usage right within the response right? Like if the response needs the request cookies to load the page.

1

There are 1 best solutions below

0
On

I suggest using HttpClient as it handles cookies for you and is just generally easier to work with. Also note that even though it’s disposable you generally should use the same HttpClient throughout your application. See: https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/