【发布时间】:2018-12-23 18:43:54
【问题描述】:
我正在尝试使用 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。有谁知道怎么回事?
【问题讨论】:
-
是什么让您认为有 cookie 被退回?
-
@DavidG 我说我在 python 中测试了相同的程序,当我尝试获取 cookie 时,我得到了 csrf 令牌。
-
@CrispApples 您是否在处理程序
handler.UseCookies上启用了cookie? -
我测试了您所拥有的并且可以重现该问题。但是,当我使用您列出的根域调用其他 URL 时,容器中会返回 cookie。
标签: c# cookies spotify dotnet-httpclient cookiecontainer