Asp.Net FormsAuth cookie不会持久化

时间:2012-05-31 18:28:34

标签: asp.net-mvc-3 asp.net-membership

我遇到的问题是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);

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我认为你需要设置HttpCookie的到期时间......

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
        {
            HttpOnly = true,
            Secure = FormsAuthentication.RequireSSL,
            Path = FormsAuthentication.FormsCookiePath,
            Expires=  = DateTime.UtcNow.AddHours(6);
        };