18

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

代码

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;
}
4

1 回答 1

23

奇怪...您是否尝试直接使用 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; }
}
于 2013-08-01T02:11:04.323 回答