我正在使用C#和MVC5使用以下代码创建自己的cookie:
// Prepare the ticket
HttpContext.Response.Cookies.Clear();
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1,
"MYNAME",
DateTime.Now,
DateTime.Now.AddDays(10), // <<- Expires 10 days
true,
null);
// Encrpt the ticket
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
// Create new cookie
HttpCookie cookie = new HttpCookie("MYNAME", encryptedCookie);
cookie.Path = FormsAuthentication.FormsCookiePath;
// Send the Cookie back to the browser
HttpContext.Response.Cookies.Add(cookie);
在Web.Config上,我将名称设置为
<authentication mode="Forms">
<forms name="MYNAME" loginUrl="~/Account/Login"></forms>
</authentication>
但是,当我查看 Firebug 时, Cookie 显示为“MYNAME”,但“过期”设置为会话即可。
事实上,当我关闭浏览器时,cookie消失了,当我回到网站时,我总是要再次登录。所有其他浏览器也是如此。
我做错了什么?
答案 0 :(得分:1)
问题在于我将“过期”设置为“票证”级别,而不是“Cookie”级别。
添加
cookie.Expires = ticket.Expiration;
..解决了问题!!
因此整个代码应如下所示:
// Prepare the ticket
HttpContext.Response.Cookies.Clear();
FormsAuthenticationTicket ticket =
new FormsAuthenticationTicket(1,
"MYNAME",
DateTime.Now,
DateTime.Now.AddDays(10), // <<- Expires 10 days
true,
null);
// Encrpt the ticket
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
// Create new cookie
HttpCookie cookie = new HttpCookie("MYNAME", encryptedCookie);
cookie.Path = FormsAuthentication.FormsCookiePath;
// THE MISSING LINE IS THIS ONE
cookie.Espires = ticket.Expiration; // <<- Uses current Ticket Expiration
// Send the Cookie back to the browser
HttpContext.Response.Cookies.Add(cookie);
答案 1 :(得分:0)
它与其他浏览器的关系如何? Chrome,IE? 如果它在那里工作正常,那么它也应该在FF上工作。 如果它不起作用那么可能存在代码问题
看看这些文章 FormsAuthenticationTicket expires too soon
基本的 http://www.codeproject.com/Articles/244904/Cookies-in-ASP-NET http://msdn.microsoft.com/en-us/library/ms178194.ASPX
由于