C # Use HttpWebRequest to submit ASP. NET forms and keep Session and Cookie

Source: Internet
Author: User
For various reasons, we sometimes need to capture some information from the Internet, some pages can be opened directly, and some pages can be opened only after login. This document describes a complete example of using HttpWebRequest and HttpWebResponse to automatically submit ASP. NET forms and maintain Session and Cookie.

Three pages are involved: MyLogin.aspx,LoginOK.htm, Default. aspx:
1) The MyLogin. aspx page MyLogin. aspx page is the logon page. If the user name and password are correct, the Session and Cookie (LoginSession and LoginCookie) are generated, and then the LoginOK.htm page is switched.

2)LoginOK.htm page

The LoginOK.htm page is a jump page. After a few seconds, it will automatically jump to the Default. aspx page.

3) Default. aspx page

The Default. aspx page is the main interface. When the main interface is opened, the system checks whether the values of LoginSession and LoginCookie are correct and displays the values of Session and Cookie.

The code for submitting an ASP. NET form (that is, completing Automatic Logon) is as follows:
Try
{
CookieContainer cookieContainer = new CookieContainer ();

//////////////////////////////////////// ///////////
// 1. Open the MyLogin. aspx page and get GetVeiwState & EventValidation
//////////////////////////////////////// ///////////
// Set parameters for opening the page
String URI = "http: // localhost: 1165/WebTest/MyLogin. aspx ";
HttpWebRequest request = WebRequest. Create (URI) as HttpWebRequest;
Request. Method = "GET ";
Request. KeepAlive = false;

// Receive the returned page
HttpWebResponse response = request. GetResponse () as HttpWebResponse;
System. IO. Stream responseStream = response. GetResponseStream ();
System. IO. StreamReader reader = new System. IO. StreamReader (responseStream, Encoding. UTF8 );
String srcString = reader. ReadToEnd ();

// Obtain the VeiwState of the page
String viewStateFlag = "id = \" _ VIEWSTATE \ "value = \"";
Int I = srcString. IndexOf (viewStateFlag) + viewStateFlag. Length;
Int j = srcString. IndexOf ("\" ", I );
String viewState = srcString. Substring (I, j-I );

// Obtain EventValidation of the page
String eventValidationFlag = "id = \" _ EVENTVALIDATION \ "value = \"";
I = srcString. IndexOf (eventValidationFlag) + eventValidationFlag. Length;
J = srcString. IndexOf ("\" ", I );
String eventValidation = srcString. Substring (I, j-I );
//////////////////////////////////////// ///////////
// 2. Automatically fill and submit the MyLogin. aspx page
//////////////////////////////////////// ///////////
// Text of the submit button
String submitButton = "Logon"; // user name and password
String userName = "1 ";
String password = "1"; // convert the text into a URL encoded string
ViewState = System. Web. HttpUtility. UrlEncode (viewState );
EventValidation = System. Web. HttpUtility. UrlEncode (eventValidation );
SubmitButton = System. Web. HttpUtility. UrlEncode (submitButton); // string data to be submitted. Format: user = uesr1 & password = 123
String formatString =
"UserName = {0} & password = {1} & loginButton = {2} & __ VIEWSTATE = {3} & __ EVENTVALIDATION = {4 }";
String postString =
String. Format (formatString, userName, password, submitButton, viewState, eventValidation); // converts the submitted string data to a byte array.
Byte [] postData = Encoding. ASCII. GetBytes (postString); // you can specify parameters for submission.
Request = WebRequest. Create (URI) as HttpWebRequest;
Request. Method = "POST ";
Request. KeepAlive = false;
Request. ContentType = "application/x-www-form-urlencoded ";
Request. CookieContainer = cookieContainer;
Request. ContentLength = postData. Length; // submit the request data
System. IO. Stream outputStream = request. GetRequestStream ();
OutputStream. Write (postData, 0, postData. Length );
OutputStream. Close (); // receives the returned page
Response = request. GetResponse () as HttpWebResponse;
ResponseStream = response. GetResponseStream ();
Reader = new System. IO. StreamReader (responseStream, Encoding. GetEncoding ("GB2312 "));
SrcString = reader. ReadToEnd ();
Foreach (Cookie cookie in response. Cookies)
CookieContainer. add (cookie ); //////////////////////////////////////// ///////////
// 3. Open the Default. aspx page
//////////////////////////////////////// ///////////
// Set parameters for opening the page
URI = "http: // localhost: 1165/WebTest/Default. aspx ";
Request = WebRequest. Create (URI) as HttpWebRequest;
Request. Method = "GET ";
Request. KeepAlive = false;
Request. CookieContainer = cookieContainer; // receives the returned page
Response = request. GetResponse () as HttpWebResponse;
ResponseStream = response. GetResponseStream ();
Reader = new System. IO. StreamReader (responseStream, Encoding. UTF8 );
SrcString = reader. readToEnd (); //////////////////////////////////////// ///////////
// 4. Analyze the returned page
//////////////////////////////////////// ///////////
//
}
Catch (WebException we)
{
String msg = we. Message;
}

The Cookie container (CookieContainer) is used to maintain the Session and Cookie. For details, see the red code section.

All source code: http://files.cnblogs.com/gotolnc/AutoPostWithCookies.rar

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.