简体   繁体   English

发送带有数据的HTTP请求并使用C#提交asp.net表单

[英]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 : 我需要使用POST方法将HTTP请求发送到Asp.Net表单,该表单是一个包含3个控件的登录表单:

  1. TextBox for username (with name="x" and id="IX"). 用户名的文本框(名称=“ x”和id =“ IX”)。
  2. TextBox for Password (With name="P" and id="IP"). 密码的文本框(名称=“ P”和id =“ IP”)。
  3. Button Submit (with name="S" and id="IS"). 按钮提交(名称=“ S”和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. 当检索字符串SourceCode时,它返回登录页面的HTML,尽管它应返回成功提交登录后重定向到它的首页。

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. 使用cookiecontainer获取响应cookie。 then send request to homepage with same cookie container. 然后使用相同的Cookie容器将请求发送到首页。

If your login request is successfull, Response may add cookie to response. 如果您的登录请求成功,Response可能会将cookie添加到响应中。 So you can use same cookie on everypage 因此您可以在每个页面上使用相同的cookie

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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