views:

550

answers:

1

Hi,

I have a few HttpWebRequests and HttpWebResponses chained together, also using CookieContainer.

The code simulates a user going through three different 'I agree' pages which set the cookie info, logging in with username and password on a fourth, and doing a POST (search) on the fifth returning the response as a string.

Is there a way I can maintain the HttpWebRequest object as 'logged in' to avoid going through those steps each time any user performs a search?

Can I set it up as static, and if its null or lacking cookie info it can run through all steps otherwise just do the post the user requires? What is a good pattern for this?.

+3  A: 

If the server you are logging in to uses cookie based authentication then you must create a System.Net.CookieContainer where you store the authentication cookie. This is quite simple:

CookieContainer container = new CookieContainer();

// Create web request
request.CookieContainer = container;

// Create next web request
nextRequest.CookieContainer = container;

// And so on
...

Just reuse the CookieContainer object for all your HttpWebRequest objects, and keep it in memory for later use.

The CookieContainer is Serializable, so you can persist it on disk if you need to. That will allow you to keep your cookie(s) even when your user restarts your application.

Alternatively, if the page doesn't use cookies but stores the session id in the url instead, you need to keep pass along the session id in the url of the pages you wisit. Just append it to the url's and it should work. :-)

Rune Grimstad
Thanks, I am using a static CookieContainer now, which logs in when null or 0 cookies. How can I check if the cookies expire or somehow become invalid, calling the need to login again and resave the cookieContainer?
CRice
I posted another question about this:http://stackoverflow.com/questions/1041851/how-to-determine-session-timeout-using-when-reusing-cookiecontainer
CRice