1

我在浏览器会话中没有保留 cookie 时遇到问题。如果我关闭并重新打开浏览器,cookie 不会在下一次请求时传递给服务器。

这是我在用户登录时创建 cookie 的方式:

var ticket = new FormsAuthenticationTicket(
    1 /*version*/,
    user.Id,
    now,
    now.Add(ExpirationTimeSpan), /* ExpirationTimeSpan = TimeSpan.FromHours(6) */
    true /*createPersistentCookie*/,
    userData,
    FormsAuthentication.FormsCookiePath);

var encryptedTicket = FormsAuthentication.Encrypt(ticket);

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
                    {
                        HttpOnly = true,
                        Secure = FormsAuthentication.RequireSSL,
                        Path = FormsAuthentication.FormsCookiePath
                    };
if (FormsAuthentication.CookieDomain != null)
{
    cookie.Domain = FormsAuthentication.CookieDomain;
}

var httpContext = this.contextAccessor.Current();
httpContext.Response.Cookies.Add(cookie);

我究竟做错了什么?

4

1 回答 1

0

我认为您需要像这样设置 HttpCookie 的过期时间......

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
        {
            HttpOnly = true,
            Secure = FormsAuthentication.RequireSSL,
            Path = FormsAuthentication.FormsCookiePath,
            Expires=  = DateTime.UtcNow.AddHours(6);
        };
于 2012-05-31T20:45:47.310 回答