问题
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?.
回答1:
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. :-)
来源:https://stackoverflow.com/questions/1036854/httpwebrequest-and-httpwebresponse-maintaining-state-of-logged-in-request-for