简体   繁体   中英

Session lost when saving cookie

Upon successful login I want to save a cookie which contains username.

The cookie saves correctly and loads username correctly but loses session!

The code to retreive username is:

if (Request.Cookies["userName"] != null)
{
  txtEmail.Text = Request.Cookies["username"].Value;
  chkRemember.Checked = true;
}

The code to save username is:

HttpCookie aCookie = new HttpCookie("username");
aCookie.Value = txtEmail.Text;
aCookie.Expires = DateTime.Now.AddYears(5);
Response.Cookies.Add(aCookie);

Any help will be greatly appreciated, Thank you

Bit of a wild shot, but are you moving from https to http? Eg login form is https, following page is http

If so most browser will ditch session cookies.

Thanks, Fran

I saw an article recently that suggested that underscores in page names can cause problems in cookies, I haven't looked into this but it might be worth checking.

Alternatively, are you clearing your cookies if the user does not choose to be remembered?

I've seen an old example recently on MSDN showing delete method that will trash your session... read the article .

If so be sure to only delete the cookie for the login otherwise you might be losing the cookie containing the sessionid.

A (very)quick translation into csharp of the article code:

    for (int i = 0; i < limit; i++)
    {
        cookieName = Request.Cookies[i].Name;
        aCookie = new HttpCookie(cookieName);
        aCookie.Expires = DateTime.Now.AddDays(-1);
        Response.Cookies.Add(aCookie);
    }

With the solution being adding a check on the cookie name.

    for (int i = 0; i < limit; i++)
    {
        cookieName = Request.Cookies[i].Name;
        if (cookieName == "username")
        {
            aCookie = new HttpCookie(cookieName);
            aCookie.Expires = DateTime.Now.AddDays(-1);
            Response.Cookies.Add(aCookie);
        }
    }

Also don't forget you can use subkeys within cookies.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM