Posted By

BlueCockatoo on 05/05/08


Tagged

c aspnet ViewState


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

umang_nine
uday1302


Screen Scraping, ViewState, and Authentication using ASP.Net


 / Published in: C#
 

URL: http://odetocode.com/articles/162.aspx

How to use WebClient to post to an ASP.Net page and maintain viewstate for proxy purposes.

  1. byte[] response;
  2.  
  3. WebClient webClient = new WebClient();
  4. response = webClient.DownloadData(LOGIN_URL);
  5.  
  6. string viewstate = ExtractViewState(
  7. Encoding.ASCII.GetString(response)
  8. );
  9.  
  10. string postData = String.Format(
  11. "__VIEWSTATE={0}&UsernameTextBox={1}&PasswordTextBox={2}&LoginButton=Login",
  12. viewstate, USERNAME, PASSWORD);
  13.  
  14. webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
  15. response = webClient.UploadData(
  16. LOGIN_URL, "POST", Encoding.ASCII.GetBytes(postData)
  17. );
  18.  
  19. private string ExtractViewState(string s)
  20. {
  21. string viewStateNameDelimiter = "__VIEWSTATE";
  22. string valueDelimiter = "value=\"";
  23.  
  24. int viewStateNamePosition = s.IndexOf(viewStateNameDelimiter);
  25. int viewStateValuePosition = s.IndexOf(
  26. valueDelimiter, viewStateNamePosition
  27. );
  28.  
  29. int viewStateStartPosition = viewStateValuePosition +
  30. valueDelimiter.Length;
  31. int viewStateEndPosition = s.IndexOf("\"", viewStateStartPosition);
  32.  
  33. return HttpUtility.UrlEncodeUnicode(
  34. s.Substring(
  35. viewStateStartPosition,
  36. viewStateEndPosition - viewStateStartPosition
  37. )
  38. );
  39. }

Report this snippet  

You need to login to post a comment.