0

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?

MethodMan
  • 18,625
  • 6
  • 34
  • 52
yair
  • 43
  • 8

1 Answers1

1

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?

Community
  • 1
  • 1
brduca
  • 3,573
  • 2
  • 22
  • 30
  • thath what im getting: https://s12.postimg.io/6f4xx62q5/stack.png ,i have a couple of questions:1.how can i know that the login is successful?(should the result be the Grades.aspx?) 2.what to write in the keyValuePair,i have alot of paramteres.. – yair Aug 24 '16 at 07:09
  • You know that it is success operation by the Http Status of the response. "result" has a property "IsSuccessStatusCode". Take a look at the content, it is an array so you can have multiple values being passed. Just updated the example. – brduca Aug 24 '16 at 08:29
  • So i tried your suggestion with a couple changes to the parameters like i saw in the link above , that is what i wrote : http://pastebin.com/J5DnBrtY , it gave me an OK response but with the login page URL . I tried to enter wrong username and it still gave me successful response. – yair Aug 24 '16 at 09:06
  • Success means that your call has returned a 200 code, your service (in case of wrong password) should return something like a 401. https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html – brduca Aug 24 '16 at 09:08
  • That is weird, what could be the problem? this is what is bugging me now the pass 2 days. I'm trying to log in and i can't get the front page from the server always getting the login page over and over. – yair Aug 24 '16 at 09:20
  • This is an authentication problem, by default if it cannot create an auth session you will be redirected to login. Put a breakpoint in your service to see if it passes the authentication. – brduca Aug 24 '16 at 09:24
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/121706/discussion-between-yair-and-brduca). – yair Aug 24 '16 at 09:31