Anton Gildebrand
Anton Gildebrand

Reputation: 3707

C# program doesn't seem to save cookies

I'm trying to make a request to a page, and save the cookie that the page responds with. If i browse to http://mydomain.com/mypage.aspx?GUID=4579 manually and debugging the responds in Fiddler, i can see that the page responds with a cookie. So, why doesn't my code save that cookie? Here is my code:

const string baseUri = "http://mydomain.com/mypage.aspx?GUID=4579";
CookieContainer cookie = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseUri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
request.CookieContainer = cookie;
response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
StreamReader reader = new StreamReader(response.GetResponseStream());
string cookiePage = reader.ReadToEnd();
reader.Close();
Console.WriteLine(cookie.Count);

Upvotes: 0

Views: 279

Answers (1)

SLaks
SLaks

Reputation: 887797

You need to set the CookieContainer before getting the response.
Once you do that, everything will happen automatically

Upvotes: 2

Related Questions