// Create our variablesstring signinUrl = "http://yourUrl.net/Login.aspx";string contentUrl = "http://yourUrl.net/Default.aspx";string responseHtml = null;CookieContainer cookies = new CookieContainer();// 1. Initialize our connection and retrieve the Viewstate.HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(signinUrl); httpWebRequest.Method = "GET";httpWebRequest.ContentType = "text/html; charset=utf-8";StreamReader responseReader = new StreamReader( httpWebRequest.GetResponse().GetResponseStream() );responseHtml = responseReader.ReadToEnd(); responseReader.Close(); // 2. Append to our Viewstate our authenitication requirements.// Determine where in responseHtml VIEWSTATE is get just the value of it.// 7 is the length of the string value="int beginPosition = responseHtml.IndexOf( "value=\"", responseHtml.IndexOf("__VIEWSTATE") ) + 7; int endPosition = responseHtml.IndexOf( "\"", beginPosition );// Convert into a Unicode string for the HTTP stream.string viewState = HttpUtility.UrlEncodeUnicode( responseHtml.Substring( beginPosition, endPosition - beginPosition ) ); // Create our new ViewState with our POST datastring post = String.Format("__VIEWSTATE={0}" + "&tbxUserName={1}&tbxPassword={2}&tbxCompany={3}&btnLogin=Login", viewState, "myUserName", "myPa$$word", "MyCompany");// 3. Post our new request to the authentication page.httpWebRequest = (HttpWebRequest)WebRequest.Create(signinUrl);httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/x-www-form-urlencoded";// Set any headers you may desirehttpWebRequest.Headers.Set("Pragma","no-cache");httpWebRequest.CookieContainer = cookies; // Add our modifications to our request streamStreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());requestWriter.Write(post);requestWriter.Close();// Close the RequestStream before the nexthttpWebRequest.GetResponse().Close();// 4. Send our final request for the protected page.httpWebRequest = (HttpWebRequest)WebRequest.Create(contentUrl);httpWebRequest.CookieContainer = cookies;responseReader = new StreamReader(httpWebRequest.GetResponse().GetResponseStream());responseHtml = responseReader.ReadToEnd();responseReader.Close(); // At this point, we have a string representation of our protected HTML page.// do something with responseHtml;
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010 MuellerDesigns.net
Sign In