I'm having a problem passing cookies in ASP.NET to a new URL. I add cookies to the Response like so:
Response.Cookies.Add(new HttpCookie("Username", Username.Text));
I then issue a redirect:
Response.Redirect(returnURL);
On the new page that I am redirected to, the cookie collection is empty. I try to retrieve a cookie like so:
Request.Cookies["Username"].Value;
Can anyone think of why the cookies are not being passed?
EDIT:
Further info I forgot to add - on the second attempt within the same browser session, the cookies ARE passed correctly with the redirect.
EDIT #2: I have found that if I use "localhost" instead of the actual domain name in the redirect URL, then the cookies are passed correctly on first login. So its only when the redirect URL is the actual domain name that it doesn't work. Strange.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["AcceptsCookies"] == null)
{
Response.Cookies["TestCookie"].Value = "ok";
Response.Cookies["TestCookie"].Expires =
DateTime.Now.AddMinutes(1);
Response.Redirect("TestForCookies.aspx?redirect=" +
Server.UrlEncode(Request.Url.ToString()));
}
else
{
Label1.Text = "Accept cookies = " +
Server.UrlEncode(
Request.QueryString["AcceptsCookies"]);
}
}
}
This link will help you understand reading and writing cookies in C#.
Also, this page would be useful in case you are familiar with VB more than C#.