HttpClient Not Saving Cookies

本文关键字:Cookies Saving Not HttpClient | 更新日期: 2023-09-27 18:25:41

我正在使用新的HttpClient来处理我的项目的网络冲浪需求;然而,尽管设置正确,HttpClient不会将Cookie保存到Cookie容器中,并且始终为空。

代码

private CookieContainer _cookieContainer = new CookieContainer();
private HttpClient HttpClient { get; set; }
private HttpClientHandler HttpClientHandler { get; set; }
public Initialize()
{
    HttpClientHandler = new HttpClientHandler
                            {
                                AllowAutoRedirect = true,
                                UseCookies = true,
                                CookieContainer = _cookieContainer
                            };
    HttpClient = new HttpClient(HttpClientHandler);
}
public CookieContainer Cookies
{
    get { return _cookieContainer; }
    set { _cookieContainer = value; }
}
public void TEST()
{
    //This is always empty, although I am sure that the site is saving login cookies
    var cookies = Cookies;
}

HttpClient Not Saving Cookies

奇怪。。。您是否尝试直接使用HttpClientHandler的CookieContainer?

代码:

public Initialize()
{
    HttpClientHandler = new HttpClientHandler
                            {
                                AllowAutoRedirect = true,
                                UseCookies = true,
                                CookieContainer = new CookieContainer()
                            };
    HttpClient = new HttpClient(HttpClientHandler);
}
public CookieContainer Cookies
{
    get { return HttpClientHandler.CookieContainer; }
    set { HttpClientHandler.CookieContainer = value; }
}

您可能还需要自动解压缩响应。看看我的答案:https://stackoverflow.com/a/74750572/1158313

我使用的示例:

var clientHandler = new HttpClientHandler {
    AllowAutoRedirect = true,
    UseCookies = true,
    CookieContainer = cookieContainer,
    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
};