Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse HttpWebResponse.Headers.Keys for a Set-Cookie session id returned

Tags:

I'm trying to create an HttpWebRequest/HttpWebResponse session with an ASP.NET website to later parse an HTML form through url params (this part I know how to do), but I do not understand how to parse and set a cookie such as the session id. In Fiddler, it shows that the ASP.NET Session ID is returned through Set-Cookie in the response to the request to the / path of the url, but how can I extract this session id and set it as a cookie for the next HttpWebRequest? I understand that this Set-Cookie header would be found in HttpWebResponse.Headers.Keys, but is there a direct path to parsing it? Thanks!

like image 961
Maxim Zaslavsky Avatar asked Jun 28 '09 21:06

Maxim Zaslavsky


2 Answers

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

like image 125
Dan Herbert Avatar answered Jan 01 '23 22:01

Dan Herbert


The answer from Dan Herbert helped me really. I appreciate your help.

Just want to post my usage - hope it helps some one at some point of time. My requirement is that I need to send back cookies from first http post response to second http post request.

1st:

CookieContainer cookieJar = new CookieContainer(); request.CookieContainer = cookieJar; ....  CookieCollection setCookies = cookieJar.GetCookies(request.RequestUri); 

2nd:

CookieContainer cc = new CookieContainer(); cc.Add(setCookies);     request.CookieContainer = cc; 
like image 44
user238397 Avatar answered Jan 01 '23 20:01

user238397