在 C# 中填写 Web 表单

Filling a Web Form in C#

我正在尝试使用 C# 自动填写 Web 表单。 这是我从旧堆栈溢出中获取的代码 post:

//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 个值要输入(用户名、密码、按钮验证)。 但是不知何故 resp 和 return 的 pageSource 总是再次登录页面。

我不知道一直在发生什么,有什么想法吗?

您正在尝试以非常困难的方式进行操作,请尝试使用 .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);
        }      
        }
    }
}

检查这个答案,可能会有帮助: