Return to Snippet

Revision: 6185
at May 5, 2008 17:21 by BlueCockatoo


Initial Code
byte[] response;

WebClient webClient = new WebClient();
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
            )
         );  
}

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

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

Initial Title
Screen Scraping, ViewState, and Authentication using ASP.Net

Initial Tags
c, aspnet

Initial Language
C#