Session and Cookie of ASP. NET form

Source: Internet
Author: User

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

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. All source code in this article: AutoPostWithCookies.rar

Three pages are involved: MyLogin.aspx,LoginOK.htm, Default. aspx:
1) MyLogin. aspx page
2)LoginOK.htm page
3) Default. aspx page

The following code submits an ASP. NET form to complete automatic logon:

 
 
  1. Try
  2. {
  3. CookieContainercookieContainer=NewCookieContainer();
  4.  
  5. //////////////////////////////////////// ///////////
  6. // 1. Open the MyLogin. aspx page and obtain VeiwState & EventValidation
  7. //////////////////////////////////////// ///////////
  8. // Set parameters for opening the page
  9. StringURI="Http: // localhost: 1165/WebTest/MyLogin. aspx";
  10. HttpWebRequestrequest= WebRequest. Create (URI) asHttpWebRequest;
  11. Request. Method="GET";
  12. Request. KeepAlive=False;
  13.  
  14. // Receive the returned page
  15. HttpWebResponseresponse=Request. GetResponse () asHttpWebResponse;
  16. System. IO. StreamresponseStream= Response. GetResponseStream ();
  17. System. IO. StreamReaderreader=NewSystem. IO. StreamReader (responseStream, Encoding. UTF8 );
  18. StringsrcString=Reader. ReadToEnd ();
  19.  
  20. // Obtain the VeiwState of the page
  21. StringviewStateFlag= "Id = \"_ VIEWSTATE\"Value= \"";
  22. Inti=SrcString. IndexOf (viewStateFlag) + viewStateFlag. Length;
  23. Intj=SrcString. IndexOf ("\" ", I );
  24. StringviewState=SrcString. Substring (I, j-I );
  25.  
  26. // Obtain EventValidation of the page
  27. StringeventValidationFlag= "Id = \"_ EVENTVALIDATION\"Value= \"";
  28. I=SrcString. IndexOf (eventValidationFlag) + eventValidationFlag. Length;
  29. J=SrcString. IndexOf ("\" ", I );
  30. StringeventValidation=SrcString. Substring (I, j-I );
  31.  
  32. //////////////////////////////////////// ///////////
  33. // 2. Automatically fill and submit the MyLogin. aspx page
  34. //////////////////////////////////////// ///////////
  35. // Text of the submit button
  36. StringsubmitButton="Login";
  37.  
  38. // User name and password
  39. StringuserName="1";
  40. Stringpassword="1";
  41.  
  42. // Convert the text into a URL encoded string
  43. ViewState=System. Web. HttpUtility. UrlEncode (viewState );
  44. EventValidation=System. Web. HttpUtility. UrlEncode (eventValidation );
  45. SubmitButton=System. Web. HttpUtility. UrlEncode (submitButton );
  46.  
  47. // String data to be submitted. Format: User=Uesr1&Password=123 
  48. StringformatString=
  49. "UserName = {0} & password = {1} & loginButton = {2} & __ VIEWSTATE = {3} & __ EVENTVALIDATION = {4 }";
  50. StringStringpostString=
  51. String. Format (formatString, userName, password, submitButton, viewState, eventValidation );
  52.  
  53. // Convert the submitted string data to a byte array
  54. Byte []PostData=Encoding. ASCII. GetBytes (postString );
  55.  
  56. // Set parameters for submission
  57. Request=WebRequest. Create (URI) asHttpWebRequest;
  58. Request. Method="POST";
  59. Request. KeepAlive=False;
  60. Request. ContentType="Application/x-www-form-urlencoded";
  61. Request. CookieContainer=CookieContainer;
  62. Request. ContentLength=PostData. Length;
  63.  
  64. // Submit request data
  65. System. IO. StreamoutputStream=Request. GetRequestStream ();
  66. OutputStream. Write (postData, 0, postData. Length );
  67. OutputStream. Close ();
  68.  
  69. // Receive the returned page
  70. Response=Request. GetResponse () asHttpWebResponse;
  71. ResponseResponseStream= Response. GetResponseStream ();
  72. Reader=NewSystem. IO. StreamReader (responseStream, Encoding. GetEncoding ("GB2312 "));
  73. SrcString=Reader. ReadToEnd ();
  74.  
  75. //////////////////////////////////////// ///////////
  76. // 3. Open the Default. aspx page
  77. //////////////////////////////////////// ///////////
  78. // Set parameters for opening the page
  79. URI="Http: // localhost: 1165/WebTest/Default. aspx";
  80. Request=WebRequest. Create (URI) asHttpWebRequest;
  81. Request. Method="GET";
  82. Request. KeepAlive=False;
  83. Request. CookieContainer=CookieContainer;
  84.  
  85. // Receive the returned page
  86. Response=Request. GetResponse () asHttpWebResponse;
  87. ResponseResponseStream= Response. GetResponseStream ();
  88. Reader=NewSystem. IO. StreamReader (responseStream, Encoding. UTF8 );
  89. SrcString=Reader. ReadToEnd ();
  90.  
  91. //////////////////////////////////////// ///////////
  92. // 4. Analyze the returned page
  93. //////////////////////////////////////// ///////////
  94. //
  95. }
  96. Catch (WebExceptionwe)
  97. {
  98. Stringmsg=We. Message;
  99. }


Note:
1) The Cookie container CookieContainer is used to maintain the Session and Cookie. For details, see the red code section.
2) When you POST an ASP. NET page, you need to POST the VeiwState and EventValidation data together. The above introduces ASP. NET forms and maintains Session and Cookie

  1. Analysis of Theme functions in ASP. NET development skills
  2. ASP. NET Dynamic Compilation
  3. Analysis on ASP. NET supported by Apache
  4. Introduction to ASP. NET Server standard controls
  5. Analysis on SQL Server Database Backup Recovery in ASP. NET

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.