保存cookie时会话丢失

Gar*_*ams 5 c# asp.net cookies session

成功登录后,我想保存一个包含用户名的cookie.

cookie正确保存并正确加载用户名但丢失会话!

retreive用户名的代码是:

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

保存用户名的代码是:

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

非常感谢任何帮助,谢谢

Mac*_*ack 1

我最近看到一篇文章建议页面名称中的下划线可能会导致 cookie 出现问题,我还没有研究过这一点,但可能值得检查一下。

或者,如果用户不选择被记住,您是否会清除 cookie?

我最近在 MSDN 上看到一个旧示例,其中显示的删除方法会破坏您的会话...阅读这篇文章

如果是这样,请确保只删除登录的 cookie,否则您可能会丢失包含 sessionid 的 cookie。

文章代码的(非常)快速翻译为 csharp:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

解决方案是添加对 cookie 名称的检查。

    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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

另外不要忘记您可以在 cookie 中使用子项。