我需要訪問Cookie以獲取用戶和密碼,然後將它們設置在Login視圖的文本框中,因爲在該視圖中選中了「記住我」。C#MVC 5在表單身份驗證登出時清除票證cookie
註銷等方法
public ActionResult LogOff()
{
//Session.Abandon();
// sign out.
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Login");
}
初始化成功登錄後,會話和餅乾。登入查看 我有當我第一次先註銷,然後嘗試訪問cookie的問題,而是因爲我運行它返回null
private void InitializeSessionVariables(AgentDTO user)
{
// SessionModel.AgentId = user.ID;
Response.Cookies.Clear();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,user.MobilePhone,DateTime.Now,DateTime.Now.AddDays(30),true,"",FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Name of auth cookie (it's the name specified in web.config) // Hashed ticket
authenticationCookie.Expires = DateTime.Now.AddDays(365);
// Add the cookie to the list for outbound response
Response.Cookies.Add(authenticationCookie);
}
操作結果「FormsAuthentication.SignOut();」
public ActionResult Index(LogonDTO model, string message = null, string reason = null)
{
if (SessionModel.AgentMobilePhone != null) return RedirectToAction("Index", "Home");
if (reason != null) message = "Su sessión ha expirado. Vuelva a loguearse.";
ViewBag.Message = message;
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
model.Username = authTicket.Name;
//model.Password = "in progress..."
}
return View(model);
}
按照這篇文章:https://support.microsoft.com/en-us/help/910443/understanding-the-forms-authentication-ticket-and-cookie,'FormsAuthentication.SignOut();'將刪除在任何情況下的cookie。我假設在持久性cookie的情況下,您根本不會調用FormsAuthentication.SignOut();'。 – Patrick
所以,在我的情況下,我應該從來沒有清潔餅乾? – Necroimix
我相信'FormsAuthentication.SignOut();'應該只用於,如果用戶仍然有票/ cookie但您的服務器上沒有打開的會話。這將從用戶的瀏覽器中刪除票證,並強制他再次「登錄」。 – Patrick