views:

120

answers:

1

I am attempting to retrieve the ASPXAUTH cookie pro grammatically without success. A similar question posted to this forum did not prove helpful.

My code is shown below. One known gotcha is to be sure to assign a CookieContainer to the request, which I have done. Additionally, I can run web application in the debugger and see that the request is valid -- the user is indeed authenticated and FormsAuthentication.SetAuthCookie() is called.

My code is shown below. In the final line, response.Cookies is always empty (using and close() statements removed for brevity).

Thanks in advance.


EDITS per stevemegson:

  1. No, the response.Headers collection does not contain the "Set-Cookie" header
  2. Amazing! If I query the CookieContainer, the cookie is indeed present:

    (not sure why this won't format?)
    CookieCollection cookies = cookieContainer.GetCookies(new Uri(BaseUri)); Cookie cookie = null; foreach (Cookie c in cookies) { if (c.Name == ".ASPXAUTH") { cookie = c; break; } } return cookie;


Original Code:

string uri = string.Format("{0}/Account.aspx/LogOn", BaseUri);
CookieContainer cookieContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.CookieContainer = cookieContainer;
request.Method = "POST";
string postData = string.Format("UserName={0}&Password={1}&RememberMe=true", UserName, Password);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Cookie cookie = response.Cookies[".ASPXAUTH"];  // Collection is always empty; returns null!!
+1  A: 

Nothing looks obviously wrong, but the next things I'd check are:

Can you see the Set-Cookie header if you read the contents of response.Headers? You don't really want to parse the cookie value out of the header if you can avoid it, but this will confirm that the header is at least getting back OK.

Can you see the cookie if you query the CookieContainer directly with cookieContainer.GetCookies(request.RequestUri)?

stevemegson
See edits above. I can indeed retrieve the cookies by calling cookieContainer.GetCookies(). This doesn't answer why response.Cookies is empty, but it solves my immediate problem. Many thanks.
Brett