通过post方法返回的Webrequest 404 Not Found

时间:2015-10-04 22:11:37

标签: c# asp.net post webrequest

像tittle说的那样,我试图通过帖子向某个页面发出请求。首先使用谷歌开发人员工具,检查请求的参数,我可以弄明白(我不完全确定我是否在我的帖子字符串中放入所有正确的参数 - 检查图像以获取更多信息)。我在www周围找到了许多例子,但是没有人使用这个例子而且我不知道什么是错的,我会像总是有点帮助一样:)。

请求标题

header_post

表单数据

form_data

这是我的代码:

string email = "xxxxx";
string password = "xxxxx";

string LOGIN_URL = "https://intranet.cibertec.edu.pe/LoginBolsa/LoginBolsaCIB.aspx";

CookieContainer cookies = new CookieContainer();

HttpWebRequest webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.CookieContainer = cookies;
StreamReader responseReader = new StreamReader(
      webRequest.GetResponse().GetResponseStream()
   );
string responseData = responseReader.ReadToEnd();
responseReader.Close();

string postString = string.Format("ctl00$ContentPlaceHolder1$Login1$UserName={0}&ctl00$ContentPlaceHolder1$Login1$Password={1}&ctl00$ContentPlaceHolder1$Login1$LoginButton={2}&hdnOrigen={3}&hdnLinea={4}&Pagina_Principal={5}", email, password, "Ingresar", "bolsa", "I", "LoginBolsaCIB.aspx");


webRequest = WebRequest.Create(LOGIN_URL) as HttpWebRequest;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.CookieContainer = cookies;


StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(postString);
requestWriter.Close();

responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
responseReader.Close();

Response.Write(responseData);

1 个答案:

答案 0 :(得分:0)

这是因为缺少__ViewState个参数。每个请求都需要附加隐藏表单字段的参数。

int start = responseData.IndexOf("value=\"", responseData.IndexOf("name=\"__VIEWSTATE\""));
int end = responseData.IndexOf("/>", start);
string viewState = responseData.Substring(start + 7, end - start - 9);
string postString = string.Format("ctl00$ContentPlaceHolder1$Login1$UserName={0}&ctl00$ContentPlaceHolder1$Login1$Password={1}&ctl00$ContentPlaceHolder1$Login1$LoginButton={2}&hdnOrigen={3}&hdnLinea={4}&Pagina_Principal={5}", email, password, "Ingresar", "bolsa", "I", "LoginBolsaCIB.aspx");
postString += String.Concat("&__VIEWSTATE=", viewState);