2

I want to log in into a website using C# code.

Here's the html code of the example form:

<form action="http://www.site.com/login.php" method="post" name="login" id="login">
<table border="0" cellpadding="2" cellspacing="0">
<tbody>
<tr><td><b>User:</b></td><td colspan=\"2\"><b>Password:</b></td></tr>
<tr>
<td><input class="inputbg" name="user" type="text"></td>
<td><input class="inputbg" name="password" type="password"></td>
<td><input type="submit" name="user_control" value="Submit" class="buttonbg"></td>
</tr>
</tbody></table>
</form>

This is what I have tried so far with unsuccessful results:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.site.com/login.php");
request.Method = "POST";
using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
    writer.Write("user=user&password=pass&user_control=Eingabe");
}

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    stream = new StreamWriter("login.html");
    stream.Write(reader.ReadToEnd());
    stream.Close();
}

Any Ideas, why this is failing?

Joe Phillips
  • 49,743
  • 32
  • 103
  • 159
druffmuff
  • 51
  • 5
  • ummm.... what? your question lacks clarity and context. – Sky Sanders May 09 '10 at 22:13
  • Well, I do have a webpage where the html formular is uncluded. And I want to log in with c# and display the page, but in log in state. The page is for example http://www.site.com and the formular redirects to http://www.site.com/login.php . Is this clear enough? – druffmuff May 09 '10 at 22:36
  • I think he wants to write his own code that logs into the website similar to the HTML he posted. – Joe Phillips May 09 '10 at 22:37
  • Yeah that's exactly what I want to do. – druffmuff May 09 '10 at 22:43

2 Answers2

0

Look into cookiecontainer.

Websites using form-based authentication typically rely on cookies. Without setting the request's cookiecontainer it won't support cookies.

Kevin
  • 8,312
  • 4
  • 27
  • 31
0

I would suggest to use Fiddler2 to see what exact difference between POST by browser and post by you application.

Also, I prefer to use WebClient class, since it is nice abstraction om GET/POST and easy to use.

Example of code,

https://github.com/alexanderbeletsky/trackyt.api.csharp/blob/master/Trackyt.Api/Adapter/Adapter.cs

Alexander Beletsky
  • 19,453
  • 9
  • 63
  • 86