0

Cookies from CookieContainer are not added to Get or Post requests. Other headers work without a problem. What is the correct way to add cookies? I have done this before without a problem but I can't locate the error here.

var cookieContainer = new CookieContainer();

var handler = new HttpClientHandler();
handler.AllowAutoRedirect = true;
handler.UseCookies = true;
handler.CookieContainer = cookieContainer;

var baseAddress = new Uri("https://www.example.se");
cookieContainer.Add(baseAddress, new Cookie("Testing", "Test"));    
//This did not work either
//cookieContainer.Add(baseAddress, new Cookie("Testing", "Test", "/"));     

using (var client = new HttpClient(new LoggingHandler(handler)))
    {
        client.BaseAddress = baseAddress;
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36");
        client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        client.DefaultRequestHeaders.Add("Accept-Language", "sv-SE,sv;q=0.8,en-US;q=0.6,en;q=0.4");

        var getResponse = client.GetAsync("/test").Result;

        string responseString = getResponse.Content.ReadAsStringAsync().Result;
    }

LoggingHandler: https://stackoverflow.com/a/18925296/3850405

enter image description here

Community
  • 1
  • 1
Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • Can you try the Cookie ctor overload that also accepts a path as the 3rd parameter and then add "/test" as the path and then retry to see if that does render the expected result. If that works we can work back to make it work in what you initially hoped for, – rene Apr 07 '17 at 11:43

1 Answers1

0

For some reason cookies aren't in the HttpRequestMessage headers when using CookieContainer. If I checked my CookieContainer object they were there though.

var cookieList = new List<Cookie>();

foreach (Cookie cookie in cookieContainer.GetCookies(baseAddress))
{
    cookieList.Add(cookie);
}
Ogglas
  • 62,132
  • 37
  • 328
  • 418