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



我正在尝试使用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。有人知道发生了什么吗?

您需要

使用 HttpClientHandler.UseCookies 属性启用 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.
//...

我尝试使用 Console.WriteLine(response.标头)和带有 csrf 令牌的 Set-Cookie 标头已打印到控制台。因此,HttpClient 似乎不会将此标头中的 cookie 计为实际 cookie,因此不会将这些所述 cookie 添加到 CookieContainer 中。

确保自动解压缩响应。 在这里看到我的答案:https://stackoverflow.com/a/74750572/1158313

我使用的示例:

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

最新更新