2016-08-23 81 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

相關問題