C # Metro HttpClient not receiving cookie on PostAsync

I am trying to log in using .NET 4.5 HttpClient and get a cookie. I am breaking my rights before leaving the attempt and checking the CookieContainer, and it does not have cookies. However, the response sends back a status of 200.

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 do not know why this does not work. It works fine when I try to use .NET 4.

+4
source share
1 answer

Use FormUrlEncodedContent instead of StringContent with string.Format . Your code does not allow username and password to be avoided.

 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") }); 
+7
source

All Articles