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

あなたは非常に難しい方法でそれをやろうとしている、使用してみてください。ネットの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ステータスによって正常に動作していることを知っています。 "result"には "IsSuccessStatusCode"というプロパティがあります。コンテンツを見てみましょう。配列なので、複数の値を渡すことができます。ちょうど例を更新しました。 – Brduca

+0

だから私は上記のリンクで見たようないくつかのパラメータを変更してあなたの提案を試みました、それは私が書いたものです:http://pastebin.com/J5DnBrtY、それは私にOKの応答を与えましたが、ログインページのURL。間違ったユーザー名を入力しようとしましたが、それでも私は正常な応答を返しました。 – yair

関連する問題