我遇到的问题是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);
我做错了什么?
答案 0 :(得分:0)
我认为你需要设置HttpCookie的到期时间......
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Path = FormsAuthentication.FormsCookiePath,
Expires= = DateTime.UtcNow.AddHours(6);
};