简体   繁体   中英

Send HTTP request with data and submit asp.net form using C#

I need to send HTTP request using POST method to an Asp.Net form, this form is a login form includes 3 controls :

  1. TextBox for username (with name="x" and id="IX").
  2. TextBox for Password (With name="P" and id="IP").
  3. Button Submit (with name="S" and id="IS").

I tried the following code:

string getUrl = "http://url/login.aspx";
string postData = String.Format("x={0}&P={1}", "usernamevalue", "passwordvalue");
HttpWebRequest getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
getRequest.Method = WebRequestMethods.Http.Post;
getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
getRequest.AllowWriteStreamBuffering = true;
getRequest.ProtocolVersion = HttpVersion.Version11;
getRequest.AllowAutoRedirect = true;
getRequest.ContentType = "application/x-www-form-urlencoded";

byte[] byteArray = Encoding.ASCII.GetBytes(postData);
getRequest.ContentLength = byteArray.Length;
Stream newStream = getRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();

HttpWebResponse getResponse = (HttpWebResponse)getRequest.GetResponse();
using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
{
    string sourceCode = sr.ReadToEnd();
}

And when retrieving string SourceCode it returns HTML of the login page inspite it should return home page which redirected to it after submitting login successfully.

I think that the code used not submitting button, I need to fix this issue by passing data to controls and click button submit and then get response of the home page(after successful login) not the login page response.

Thanks in advance.

use cookiecontainer to get response cookie. then send request to homepage with same cookie container.

If your login request is successfull, Response may add cookie to response. So you can use same cookie on everypage

var cookieContainer = new CookieContainer();
getRequest.CookieContainer = cookieContainer;
...
//send request to login.aspx page.

HttpWebRequest homeRequest = (HttpWebRequest)WebRequest.Create(homeUrl);
homeRequest.CookieContainer  =  cookieContainer;
//send request to homepage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM