简体   繁体   English

保存cookie时会话丢失

[英]Session lost when saving cookie

Upon successful login I want to save a cookie which contains username. 成功登录后,我想保存一个包含用户名的cookie。

The cookie saves correctly and loads username correctly but loses session! cookie正确保存并正确加载用户名但丢失会话!

The code to retreive username is: retreive用户名的代码是:

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? 有点狂野,但你是否从https转向http? Eg login form is https, following page is http 例如,登录表格是https,以下页面是http

If so most browser will ditch session cookies. 如果是这样,大多数浏览器将丢弃会话cookie。

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. 我最近看到一篇文章,建议页面名称中的下划线可能会导致cookie出现问题,我没有考虑过这个问题,但可能值得一试。

Alternatively, are you clearing your cookies if the user does not choose to be remembered? 或者,如果用户不选择记住,您是否清除了Cookie?

I've seen an old example recently on MSDN showing delete method that will trash your session... read the article . 我最近在MSDN上看到了一个旧示例,显示了删除会话的删除方法... 阅读文章

If so be sure to only delete the cookie for the login otherwise you might be losing the cookie containing the sessionid. 如果是这样,请确保仅删除登录的cookie,否则您可能会丢失包含sessionid的cookie。

A (very)quick translation into csharp of the article code: (非常)快速翻译成文章代码的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);
    }

With the solution being adding a check on the cookie name. 解决方案是添加对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);
        }
    }

Also don't forget you can use subkeys within cookies. 另外请不要忘记您可以在cookie中使用子键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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