挣扎试图让Cookie不符合.net 4.5中的HttpClient的响应

我有下面的代码,成功的工作。 我无法弄清楚如何从响应中获取cookie。 我的目标是,我希望能够在请求中设置cookie,并将cookie从响应中取出。 思考?

private async Task<string> Login(string username, string password) { try { string url = "http://app.agelessemail.com/account/login/"; Uri address = new Uri(url); var postData = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password ", password) }; HttpContent content = new FormUrlEncodedContent(postData); var cookieJar = new CookieContainer(); var handler = new HttpClientHandler { CookieContainer = cookieJar, UseCookies = true, UseDefaultCredentials = false }; var client = new HttpClient(handler) { BaseAddress = address }; HttpResponseMessage response = await client.PostAsync(url,content); response.EnsureSuccessStatusCode(); string body = await response.Content.ReadAsStringAsync(); return body; } catch (Exception e) { return e.ToString(); } } 

这里是完整的答案:

  HttpResponseMessage response = await client.PostAsync(url,content); response.EnsureSuccessStatusCode(); Uri uri = new Uri(UrlBase); var responseCookies = cookieJar.GetCookies(uri); foreach (Cookie cookie in responseCookies) { string cookieName = cookie.Name; string cookieValue = cookie.Value; } 

One Solution collect form web for “挣扎试图让Cookie不符合.net 4.5中的HttpClient的响应”

要将Cookie添加到请求,请在使用CookieContainer.Add(uri, cookie)的请求之前填充cookie容器。 请求完成后,cookie容器将自动填充响应中的所有cookie。 然后你可以调用GetCookies()来检索它们。

 CookieContainer cookies = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = cookies; HttpClient client = new HttpClient(handler); HttpResponseMessage response = client.GetAsync("http://google.com").Result; Uri uri = new Uri("http://google.com"); IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>(); foreach (Cookie cookie in responseCookies) Console.WriteLine(cookie.Name + ": " + cookie.Value); Console.ReadLine(); 
  • .NET HttpClient。 如何POSTstring值?
  • 如何在.NETtesting中传递一个模拟的HttpClient?
  • ASP.NET WebApi:如何使用WebApi HttpClient执行file upload的多部分文章
  • 错误原因CS0161:不是所有的代码path都返回一个值
  • HttpClient和HttpClientHandler必须被丢弃吗?
  • HttpClient是否可以安全使用?
  • 来自.Net 4.5的asynchronousHttpClient是密集加载应用程序的不好select吗?
  • 在WebAPI客户端中每次调用创build一个新的HttpClient的开销是多less?