2016-08-23 71 views
0

我想用C#自动填充一个Web窗体。 这里是我的代码从旧的堆栈溢出后采取:在C中填写一个Web窗体#

//NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag 
string formUrl = "https://url/Login/Login.aspx?ReturnUrl=/Student/Grades.aspx"; 
string formParams = string.Format(@"{0}={1}&{2}={3}&{4}=%D7%9B%D7%A0%D7%99%D7%A1%D7%94", usernameBoxID ,"*myusernamehere*",passwordBoxID,"*mypasswordhere*" ,buttonID); 
string cookieHeader; 
WebRequest req = WebRequest.Create(formUrl); //creating the request with the form url. 
req.ContentType = "application/x-www-form-urlencoded"; 
req.Method = "POST"; // http POST mode. 
byte[] bytes = Encoding.ASCII.GetBytes(formParams); // convert the data to bytes for the sending. 
req.ContentLength = bytes.Length; // set the length 
using (Stream os = req.GetRequestStream()) 
{ 
    os.Write(bytes, 0, bytes.Length); 
} 
WebResponse resp = req.GetResponse(); 
cookieHeader = resp.Headers["Set-cookie"]; 
using (StreamReader sr = new StreamReader(resp.GetResponseStream())) 
{ 
    string pageSource = sr.ReadToEnd(); 
} 

的用户名和密码是否正确。 我看了网站的来源,它有3个值(用户名,密码,按钮验证)。 但不知何故,返回的resppageSource总是再次登录页面。

我不知道这是怎么回事,有什么想法?

回答

1

你试图做一个非常困难的方式,尝试使用的.Net的HttpClient:

using System; 
using System.Collections.Generic; 
using System.Net.Http; 

class Program 
{ 
    static void Main() 
    { 
     using (var client = new HttpClient()) 
     { 
      client.BaseAddress = new Uri("http://localhost:6740"); 
      var content = new FormUrlEncodedContent(new[] 
      { 
       new KeyValuePair<string, string>("***", "login"), 
       new KeyValuePair<string, string>("param1", "some value"), 
       new KeyValuePair<string, string>("param2", "some other value") 
      }); 

    var result = client.PostAsync("/api/Membership/exists", content).Result; 

    if (result.IsSuccessStatusCode) 
     { 
      Console.WriteLine(result.StatusCode.ToString()); 
      string resultContent = result.Content.ReadAsStringAsync().Result; 
      Console.WriteLine(resultContent); 
     } 
     else 
     { 
      // problems handling here 
      Console.WriteLine("Error occurred, the status code is: {0}", result.StatusCode); 
     }  
     } 
    } 
} 

检查这个答案,可能会有帮助:.NET HttpClient. How to POST string value?

+0

thath什么即时得到:https://开头S12 .postimg.io/6f4xx62q5/stack.png,我有几个问题:1.我怎么能知道登录成功?(应该是Grades.aspx的结果?)2.在keyValuePair中写什么,我有很多paramteres .. – yair

+0

你知道这是响应的Http状态的成功操作。 “结果”有一个属性“IsSuccessStatusCode”。看看内容,它是一个数组,因此您可以传递多个值。刚更新了这个例子。 – Brduca

+0

所以我尝试了一些改变参数的建议,就像我在上面的链接中看到的那样,这就是我写的:http://pastebin.com/J5DnBrtY,它给了我一个确定的响应,但是登录页面的URL。我试图输入错误的用户名,它仍然给我成功的回应。 – yair