简体   繁体   中英

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM