We Recommend

Accelerated C# 2008 Accelerated C# 2008
This book is both a rapid tutorial and a permanent reference. You’ll quickly master C# syntax while learning how the CLR simplifies many programming tasks. You’ll also learn best practices that ensure your code will be efficient, reusable, and robust. Why spend months or years discovering the best ways to design and code C# when this book will show you how to do things the right way, right from the start?


Ballyhoo


Posted By

BlueCockatoo on 05/05/08


Tagged

c aspnet ViewState


Versions (?)


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.