I also worked with Rohit Agarwal BrowserSession along with HtmlAgilityPack. But for me, subsequent calls to "Get-function" did not work, because every time new cookies were set. This is why I added some features myself. (My solution is far from ideal - it's just a quick and dirty fix) But it worked for me, and if you don't want to spend a lot of time researching the BrowserSession , this is what I did:
The added / changed functions are as follows:
class BrowserSession{ private bool _isPost; private HtmlDocument _htmlDoc; public CookieContainer cookiePot; //<- This is the new CookieContainer ... public string Get2(string url) { HtmlWeb web = new HtmlWeb(); web.UseCookies = true; web.PreRequest = new HtmlWeb.PreRequestHandler(OnPreRequest2); web.PostResponse = new HtmlWeb.PostResponseHandler(OnAfterResponse2); HtmlDocument doc = web.Load(url); return doc.DocumentNode.InnerHtml; } public bool OnPreRequest2(HttpWebRequest request) { request.CookieContainer = cookiePot; return true; } protected void OnAfterResponse2(HttpWebRequest request, HttpWebResponse response) { //do nothing } private void SaveCookiesFrom(HttpWebResponse response) { if ((response.Cookies.Count > 0)) { if (Cookies == null) { Cookies = new CookieCollection(); } Cookies.Add(response.Cookies); cookiePot.Add(Cookies); //-> add the Cookies to the cookiePot } }
What he does: he basically saves cookies from the initial "post-response" and adds the same CookieContainer to the request, which is called later. I donโt quite understand why it didnโt work in the original version, because it somehow does the same in the AddCookiesTo function. (if (Cookies! = null & & Cookies.Count> 0) request.CookieContainer.Add (Cookies);) In any case, it should work fine with these added functions.
It can be used as follows:
//initial "Login-procedure" BrowserSession b = new BrowserSession(); b.Get("http://www.blablubb/login.php"); b.FormElements["username"] = "yourusername"; b.FormElements["password"] = "yourpass"; string response = b.Post("http://www.blablubb/login.php");
all subsequent calls should use:
response = b.Get2("http://www.blablubb/secondpageyouwannabrowseto"); response = b.Get2("http://www.blablubb/thirdpageyouwannabrowseto"); ...
I hope this helps when you come across the same problem.
source share