使用C#HttpClient无法获取任何Cookie

时间:2018-12-23 18:43:54

标签: c# cookies spotify dotnet-httpclient cookiecontainer

我正在尝试使用C#和HttpClient类在Spotify登录页面上获取cookie。但是,当我知道正在设置cookie时,CookieContainer始终为空。我没有发送任何标头,但是它仍然应该给我cookie,因为当我使用python(请求模块)发送不带任何标头的GET请求时,我得到了csrf令牌。这是我的代码:

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
using System.Web;

class Program
{
    static void Main()
    {
        Task t = new Task(MakeRequest);
        t.Start();
        Console.WriteLine("Getting cookies!");
        Console.ReadLine();
    }

    static async void MakeRequest()
    {
        CookieContainer cookies = new CookieContainer();
        HttpClientHandler handler = new HttpClientHandler();

        handler.CookieContainer = cookies;
        Uri uri = new Uri("https://accounts.spotify.com/en/login/?_locale=en-US&continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F");
        HttpClient client = new HttpClient(handler);
        var response = await client.GetAsync(uri);
        string res = await response.Content.ReadAsStringAsync();
        Console.WriteLine(cookies.Count);
        foreach (var cookie in cookies.GetCookies(uri)) {
            Console.WriteLine(cookie.ToString());
        }
    }
}

对我来说,这似乎很简单,但是该程序始终说有0个cookie。有人知道怎么回事吗?

2 个答案:

答案 0 :(得分:1)

您需要使用HttpClientHandler.UseCookies Property

启用Cookie的使用
public bool UseCookies { get; set; }
  

获取或设置一个值,该值指示处理程序是否使用CookieContainer属性存储服务器cookie,并在发送请求时使用这些cookie。

//...

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
handler.UseCookies = true; //<-- Enable the use of cookies.

//...

答案 1 :(得分:0)

我尝试使用Console.WriteLine(response.Headers)将响应标头写入控制台,并将带有csrf令牌的Set-Cookie标头打印到控制台。因此,看来HttpClient不会将此标头中的cookie视为实际cookie,因此不会将这些cookie添加到CookieContainer中。