I'm using C# and MVC5 to create my own cookie using this code:

// 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);

On the Web.Config I set the name to be

<authentication mode="Forms">
   <forms name="MYNAME" loginUrl="~/Account/Login"></forms>
</authentication>

But when I look the Firebug, the Cookie appears as "MYNAME" but the "expires" is set to Session.
And in fact, when I close the browser, the cookie disappears and when I go back to the site, I always have to login again. The same happens with all other browsers.

What am I doing wrong??

有帮助吗?

解决方案

The problem was that I was setting the Expiration at the "Ticket" level but NOT at the "Cookie" level.

Adding

cookie.Expires = ticket.Expiration; 

..solved the issue !!

So the entire code should look like this:

// 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);

其他提示

How it goes with other browsers? Chrome, IE? If it works fine there, then it should be working on FF as well. If it doesn't work there then possibility is there is issue with code

Take a look on these articles FormsAuthenticationTicket expires too soon

Basic one http://www.codeproject.com/Articles/244904/Cookies-in-ASP-NET http://msdn.microsoft.com/en-us/library/ms178194.ASPX

Thanks

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top