C#Metro HttpClient未在PostAsync上接收cookie

时间:2012-07-26 00:34:39

标签: c# windows-8 microsoft-metro .net-4.5 dotnet-httpclient

我正在尝试使用.NET 4.5 HttpClient登录网站并接收cookie。我在离开试验之前就打破了,并检查了CookieContainer并且它不包含任何cookie。响应发回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);
    }

我不知道为什么这不起作用。当我尝试.NET 4风格时它工作正常。

1 个答案:

答案 0 :(得分:7)

FormUrlEncodedContent使用StringContent而不是string.Format。您的代码无法正确转义用户名和密码。

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