Search code examples
c#sessionwebrequest

HTTP web request doesn't maintain session


I have a program where I want to scrap some useful study material for personal use. This site maintain a session key and some other key also. If I tried to go to a nested page then it will end the session.

I'm unable to maintain session key using a web request class.

How can I maintain a session using a web request class?

Please help.


Solution

  • You need to maintain the CookiesCollection across your requests.

    var request = (HttpWebRequest)HttpWebRequest.Create("http://www.mysite.com/");
    var cookies = new CookieContainer();
    
    //Pass the collection along with each request to maintain session
    request.CookieContainer = cookies;
    

    When you get the response back, your container will automatically contain the set of cookies associated with it. You can then reuse that container with subsequent requests.