我使用較新的SimpleMembership模型創建了一個新的MVC 4 Web應用程序。 VS2012創建的「開箱即用」網站會在登錄頁面創建帳戶控制器和「記住我」複選框。但是當我檢查這個盒子時,它不記得我。如何使用MVC 4和「記住我」功能檢查cookie?
我是新來的MVC的某些部分,但它似乎沒有在我的AccountController在登錄區域檢查以前保存的cookie。我需要爲此編寫代碼嗎?我確實在另一個網站上找到了一個例子,但在實施之前,我想確保我正確地做到了這一點。
對我而言,微軟會將Remember Me功能作爲新MVC 4 Web應用程序的一部分自動執行,但不包括該部分代碼。
爲節省餅乾,我使用,我在此網站上發現了以下內容:
FormsAuthentication.SetAuthCookie(model.UserName, true);
int timeout = model.RememberMe ? 525600 : 30; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(model.UserName, model.RememberMe, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(52000);// timeout
cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);`
WebSecurity(在MVC4)已經有「記住我」功能。請參閱WebSecurity.Login – LostInComputer
正如LostInComputer所述,方法WebSecurity.Login [已允許cookie持久性](http://msdn.microsoft.com/zh-cn/library/webmatrix.webdata.websecurity.login%28v=vs.111 %29.aspx)。第三個參數被命名爲'persistCookie'並且做到這一點。默認的AccountController將該參數作爲LogInModel中'RememberMe'屬性的值傳遞。 –