HttpClient 不在 CookieContainer 中存储 cookie [英] HttpClient not storing cookies in CookieContainer

查看:29
本文介绍了HttpClient 不在 CookieContainer 中存储 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 VS2010 +.NET 4.0 + System.Net.Http(来自 Nuget).

I'm using VS2010 +.NET 4.0 + System.Net.Http (from Nuget).

由于我无法理解的原因,我在 HttpResponseMessage 中收到的会话 cookie 不会自动保存在 HttpClient CookieContainer 中.这是我的代码的样子:

For a reason which I don't manage to understand, the session cookie which I receive in my HttpResponseMessage is not automatically saved in the HttpClient CookieContainer. Here is what my code looks like:

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);

Uri site = new Uri("https://www.mywebsite.com");
var response1 = client.SendAsync(new HttpRequestMessage(HttpMethod.Get,site)).Result;

我可以在响应头中看到我有以下内容:

I can see in the response headers that I have the following:

Set-Cookie: JSESSIONID=FC8110E434C2C6DAB78B4E335024A639; Path=/member; Secure

但是我的 cookie 容器仍然是空的...为什么?

However my cookie container remains empty ...why ?

推荐答案

我想问题在于您的 cookie 安全.问题在于,CookieContainer 不会在后续 HTTP 请求中将安全 cookie 发送回服务器.这可能是一个错误,或者它背后有一些原因.

I guess the problem is that your cookies are secure. The problem is that, CookieContainer won't send secure cookies back to the server in subsequent HTTP requests. It might be a bug, or maybe it has some reasons behind it.

一种解决方法是手动将 cookie 重新添加到 CookieContainer.这样,cookie 将在 HTTP 请求标头中发送回,因为当您将 cookie 发送回服务器时,不会定义 secure.

A workaround is to re-add the cookie to CookieContainer manually. This way, cookie would be sent back in HTTP request header, as no secure would be defined when you send cookies back to the server.

有关详细信息,请参阅这篇文章.

See this article for more information.

这篇关于HttpClient 不在 CookieContainer 中存储 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆