The .NET framework will manage cookies for you. You don't have to concern yourself with parsing the cookie information out of the headers or adding a cookie header to your requests.
To store and send your session ID, use the Cookie
and CookieContainer
classes to store them and then make sure you send your cookies with every request.
The following example shows how to do this. The CookieContainer, 'cookieJar
' can be shared across multiple domains and requests. Once you add it to a request object, the reference to it will also be added to the response object when the response is returned.
CookieContainer cookieJar = new CookieContainer();
var request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
request.CookieContainer = cookieJar;
var response = request.GetResponse();
foreach (Cookie c in cookieJar.GetCookies(request.RequestUri))
{
Console.WriteLine("Cookie['" + c.Name + "']: " + c.Value);
}
The output of this code will be:
Cookie['PREF']: ID=59e9a22a8cac2435:TM=1246226400:LM=1246226400:S=tvWTnbBhK4N7Tlpu
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…