I am attempting to retrieve the ASPXAUTH cookie programmatically 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).
Responses to stevemegson:
- No, the response.Headers collection does not contain the "Set-Cookie" header
Amazing! If I query the CookieContainer, the cookie is indeed present:
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!!