HttpWebRequest and HttpWebResponse: saving request login status for consecutive requests

I have several HttpWebRequests and HttpWebResponses connected together, also using CookieContainer.

The code simulates a user going through three different "Agree" pages that set cookie information, register with a username and password in fourth place and perform POST (search) in fifth, returning the response as a string.

Is there a way to save the HttpWebRequest object as “registered” to avoid going through these steps every time any user searches?

Can I configure it as static, and if its zero or missing cookie information can be followed in all steps, otherwise just make the message that the user needs? What good is this?

+4
source share
1 answer

If the server you are accessing uses cookie-based authentication, then you must create a System.Net.CookieContainer where you store the authentication cookie. It is pretty 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 for all HttpWebRequest objects and store it in memory for later use.

CookieContainer is Serializable, so you can save it to disk if you need to. This will allow you to save cookies even when your user reloads your application.

Alternatively, if the page does not use cookies, but instead stores the session ID in the URL, you need to save the pass by session ID in the URL of the pages you see. Just add it to the url and it should work. :-)

+5
source

Source: https://habr.com/ru/post/1286663/


All Articles