0

I am sending form data in a post request which I know returns cookies but my cookie variable is being returned as empty

I've tried using GetCookies as you can see but I'm wondering if I can filter the cookies out of my PostAsync Response as I get a 200 response

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;

HttpClient client = new HttpClient(handler);
HttpContent content = new StringContent(JsonConvert.SerializeObject(formVals), Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(targetURI.AbsoluteUri , content);

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI).Cast<Cookie>()
foreach (Cookie cookie in responseCookies)
   result.Add(cookie);

I expect 2 cookies to come back and be stored in my responseCookies Container

2 Answers2

1

There are some unclear aspects in your question: where does your cookies variable come from, and where does your handler variable come from? These details are important to answer the question.

I can think of 2 possible wrong parts of your code. First, you should attach a CookieContainer to your handler:

var cookies = new CookieContainer();
var handler = new HttpClientHandler() { CookieContainer = cookies };
var client = new HttpClient(handler);
var content = new StringContent(JsonConvert.SerializeObject(formVals), Encoding.UTF8, "application/json");
var response = await client.PostAsync(targetURI.AbsoluteUri, content);

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI).Cast<Cookie>()
foreach (Cookie cookie in responseCookies)
   result.Add(cookie);

Secondly (assuming your cookies and handler variables were initialized that way), you might need to fetch cookies for the correct base address (Uri.Host):

IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetURI.Host).Cast<Cookie>()

If you are completely unsure, please check with this approach(deep inspection based on reflection) if cookies are set at all, and for which domain they are set.

AZWN
  • 158
  • 12
0

Just so you guys know, the problem was I hadn't encoded my form data. Changed content to the line below.

var content = new FormUrlEncodedContent(formVals);