/ Published in: C#
How to use WebClient to post to an ASP.Net page and maintain viewstate for proxy purposes.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
byte[] response; response = webClient.DownloadData(LOGIN_URL); string viewstate = ExtractViewState( Encoding.ASCII.GetString(response) ); string postData = String.Format( "__VIEWSTATE={0}&UsernameTextBox={1}&PasswordTextBox={2}&LoginButton=Login", viewstate, USERNAME, PASSWORD); webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); response = webClient.UploadData( LOGIN_URL, "POST", Encoding.ASCII.GetBytes(postData) ); private string ExtractViewState(string s) { string viewStateNameDelimiter = "__VIEWSTATE"; string valueDelimiter = "value=\""; int viewStateNamePosition = s.IndexOf(viewStateNameDelimiter); int viewStateValuePosition = s.IndexOf( valueDelimiter, viewStateNamePosition ); int viewStateStartPosition = viewStateValuePosition + valueDelimiter.Length; int viewStateEndPosition = s.IndexOf("\"", viewStateStartPosition); return HttpUtility.UrlEncodeUnicode( s.Substring( viewStateStartPosition, viewStateEndPosition - viewStateStartPosition ) ); }
URL: http://odetocode.com/articles/162.aspx