Search code examples
c#cookieswebrequest

HttpWebRequest resp.Headers["Set-Cookie"] is null


Update 1: Screenshot of post/get headers: http://imageshack.us/photo/my-images/826/getpost.png

I'm looking for help with a web request. The purpose of the request is to log in to a site and retrieve the Set-Cookie header. I'm grateful for any help!

I'm trying to log in to a site and retrieve the cookie value using the code below. However, the Set-Cookie header is always null:

static void Main(string[] args)
{
    string formUrl = "https://account.guildwars2.com/login";
    string formParams = string.Format("email={0}&password={1}", "xxx", "xxx");
    string cookieHeader;
    var req = (HttpWebRequest)WebRequest.Create(formUrl);
    req.Referer = "https://account.guildwars2.com/login";
    req.ContentType = "application/x-www-form-urlencoded";
    req.Method = "POST";
    req.KeepAlive = true;
    byte[] bytes = Encoding.ASCII.GetBytes(formParams);
    req.ContentLength = bytes.Length;
    using (Stream os = req.GetRequestStream())
    {
        os.Write(bytes, 0, bytes.Length);
    }
    WebResponse resp = req.GetResponse();
    cookieHeader = resp.Headers["Set-Cookie"];
}

I'm not sure if this has anything to do with redirects, because in the C# application, the response-uri is "https://account.guildwars2.com/login?redirect_uri=/download"

Response headers Chrome

  • Content-Length:0
  • Content-Type:text/html
  • Date:Sat, 29 Sep 2012 15:07:30 GMT
  • Location:download
  • Server:Microsoft-IIS/7.5
  • Set-Cookie:s=60B845F0-4E22-4A4B-890B-F3B885CEF9AE; Domain=guildwars2.com; Path=/; Version=1
  • X-Powered-By:ARR/2.5

Response from C# application

  • Content-Length: 7344
  • Content-Type: text/html
  • Date: Sat, 29 Sep 2012 15:42:44 GMT
  • Server: Microsoft-IIS/7.5
  • X-Powered-By: ARR/2.5

Solution

  • By default, HttpWebRequest automatically follows HTTP redirection responses, which prevents you from capturing the Set-Cookie header in the original response. To disable this behavior, set AllowAutoRedirect to false before sending the request:

    req.AllowAutoRedirect = false;