C# HttpClient 不在 CookieContainer 中存储 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14681144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:39:48  来源:igfitidea点击:

HttpClient not storing cookies in CookieContainer

c#cookieshttpclient

提问by user2038596

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

我使用VS2010+ .NET 4.0+ System.Net.Http(从Nuget)。

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

由于我无法理解的原因,我收到的会话 cookieHttpResponseMessage不会自动保存在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;

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

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

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

However my cookie container remains empty ...why ?

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

采纳答案by Saeed Neamati

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 不会在后续 HTTP 请求中将安全 cookie 发送回服务器。这可能是一个错误,或者它背后有一些原因。

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

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

See this articlefor more information.

有关更多信息,请参阅此文章

回答by Salar

Use this piece of code to retrieve cookies from response:

使用这段代码从响应中检索 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;
}

回答by crikey

Perhaps the problem is that your request Url path is to the root of the web site ("/"), but your Set-Cookie header indicates a Path of "/member".

也许问题在于您的请求 Url 路径指向网站的根目录(“/”),但您的 Set-Cookie 标头指示“/member”的路径。