gpt4 book ai didi

c# - HttpClient 不在 CookieContainer 中存储 cookie

转载 作者:IT王子 更新时间:2023-10-29 04:43:36 30 4
gpt4 key购买 nike

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

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

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;

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

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

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

最佳答案

使用这段代码从响应中检索 cookie:

/// <summary>
/// Read web cookies
/// </summary>
public static CookieContainer ReadCookies(this HttpResponseMessage response)
{
var pageUri = response.RequestMessage.RequestUri;

var cookieContainer = new CookieContainer();
IEnumerable<string> cookies;
if (response.Headers.TryGetValues("set-cookie", out cookies))
{
foreach (var c in cookies)
{
cookieContainer.SetCookies(pageUri, c);
}
}

return cookieContainer;
}

关于c# - HttpClient 不在 CookieContainer 中存储 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14681144/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com