cookie无法在asp.net中记住我

时间:2013-10-20 17:31:13

标签: c# asp.net cookies web-config

我使用此代码登录网站:

var userId = User.UserId;
var userData = userId.ToString(CultureInfo.InvariantCulture);
var authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), persistanceFlag, userData, FormsAuthentication.FormsCookiePath);
var encTicket = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
if (authTicket.IsPersistent)
     {
          cookie.Expires = DateTime.Now.AddMonths(6);
     }

并在web.config和此代码中使用machinekey:

<sessionState mode="InProc" timeout="20" cookieless="UseCookies" />
<httpCookies httpOnlyCookies="true" />
<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="2880" cookieless="UseCookies" />
</authentication>

但请记住我不行!我在浏览器中检查cookie,保存.ASPXAUTH并且日期到期是可以的。但几分钟后,asp.net不使用cookies是浏览器,记住我不工作!

1 个答案:

答案 0 :(得分:1)

您还希望将Cookie过期设置为与过期时相同。

...
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                HttpOnly = true,
                Secure = FormsAuthentication.RequireSSL,
                Path = FormsAuthentication.FormsCookiePath
            };
if (authTicket.IsPersistent)
{
   cookie.Expires = encTicket.Expiration;
}
if (FormsAuthentication.CookieDomain != null)
{
   cookie.Domain = FormsAuthentication.CookieDomain;
}
Response.Cookies.Add(cookie);

仅供参考:您可能希望删除default valuestimeout="20"cookieless="UseCookies"