I'm trying to get cookies on the Spotify login page with C# and the HttpClient class. However, the CookieContainer is always empty when I know cookies are being set. I'm not sending any headers, but it should still give me the cookie(s) because when I send a GET request without any headers with python (requests module) I get the csrf token. Here's my code:
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());
}
}
}
It seems pretty simple to me, but the program always says there's 0 cookies. Anyone know what's going on?
handler.UseCookies
? – MichaeuUseCookies = true
is the default setting. I suggest using a static HttpClient. Possibly aLazy<HttpClient> httpClient = new Lazy<HttpClient>(() => { HttpClientHandler handler = new HttpClientHandler { (set a new CookieContainer here or use a static one -> to store the Cookies of all "sessions") } etc }
. IMO, it works much better in all situations. – CouldServerCertificateCustomValidationCallback
). Required, when a connection usesHttps
, which might also be the problem here. – Could