Search code examples
c#formswebformswebrequestwebresponse

Filling a Web Form in C#


I'm trying to fill a web form automatically with C#. Here is my code i took from an old stack overflow 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();
}

The username and password are correct. I looked at the source of the website and it has 3 values to enter(username , password , button validation). But somehow the resp and the pageSource that return are always the login page again.

i have no idea what is that keep happening ,any ideas?


Solution

  • You are trying to do it in a very hard way, try using .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);
            }      
            }
        }
    }
    

    Check this answer, might help: .NET HttpClient. How to POST string value?