Search code examples
c#cookieshttpwebrequesthttpwebresponse

Not returning Set-Cookie parameter when using HttpWebResponse


The following code:

string url = "https://accounts.spotify.com/en/login";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = new CookieContainer();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    string source = sr.ReadToEnd();
    MessageBox.Show(source);
    MessageBox.Show(resp.Cookies.Count.ToString());

    foreach (Cookie cookie in resp.Cookies)
    {
        MessageBox.Show(cookie.Name, cookie.Value);
    }
}

Is meant to make a Message Box for each cookie with the name and value.

But it doesn't! not a single value gets returned.

Instead it does the following:

Shows the Source, the amount of Cookies (Shows 0) and then nothing else just a brief 1-2 seconds before the form loads.

It should respond with csrf_token=<...>

As you can see, even in the Fiddler response you can see the cookies. Image


Solution

  • I am not sure why resp.Cookies no having any cookies in it. But if you observe resp.Headers has one value Set-Cookie. You can use that to retrieve cookies coming in the response.

    Use following line of code to get the cookie header.

    var cookieHeader = resp.Headers["Set-Cookie"];
    

    This will give you value like

    csrf_token={sometokenvalue};Version=1;Domain=accounts.spotify.com;Path=/;Secure