Question

I am trying to log in to a website using .NET 4.5 HttpClient and receive a cookie. I break right before leaving the try and check the CookieContainer and it contains no cookies. The response sends back a 200 status though.

private async void Login(string username, string password)
{
    try
    {
        Uri address = new Uri(@"http://website.com/login.php");
        CookieContainer cookieJar = new CookieContainer();
        HttpClientHandler handler = new HttpClientHandler()
        {
            CookieContainer = cookieJar
        };
        handler.UseCookies = true;
        handler.UseDefaultCredentials = false;
        HttpClient client = new HttpClient(handler as HttpMessageHandler)
        {
            BaseAddress = address
        };

        HttpContent content = new StringContent(string.Format("username={0}&password={1}&login=Login&keeplogged=1", username, password));
        HttpResponseMessage response = await client.PostAsync(client.BaseAddress, content);
    }

I have no clue why this isn't working. It works fine when I try .NET 4 style.

Was it helpful?

Solution

Use FormUrlEncodedContent instead of StringContent with string.Format. Your code doesn't properly escape the user name and password.

HttpContent content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("username", username),
    new KeyValuePair<string, string>("password", password),
    new KeyValuePair<string, string>("login", "Login"),
    new KeyValuePair<string, string>("keeplogged", "1")
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top