0

我需要訪問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); 
} 
+0

按照這篇文章:https://support.microsoft.com/en-us/help/910443/understanding-the-forms-authentication-ticket-and-cookie,'FormsAuthentication.SignOut();'將刪除在任何情況下的cookie。我假設在持久性cookie的情況下,您根本不會調用FormsAuthentication.SignOut();'。 – Patrick

+0

所以,在我的情況下,我應該從來沒有清潔餅乾? – Necroimix

+0

我相信'FormsAuthentication.SignOut();'應該只用於,如果用戶仍然有票/ cookie但您的服務器上沒有打開的會話。這將從用戶的瀏覽器中刪除票證,並強制他再次「登錄」。 – Patrick

回答

0

您可以使用JavaScript來存儲用戶信息,如果他點擊記住複選框

使用

localStorage.setItem("UserName", "Smith"); 

設定值

和對文檔準備事件登錄頁面上Jquery寫下面的代碼

var UserName = localStorage.getItem("UserName"); 
if (UserName) $("#username").val(UserName); 

希望這會解決您的問題。

+0

在本地存儲中,我無法保存密碼。 – Necroimix

+0

使用SessionID在服務器端存儲密碼。您可以發送帶有SessionID的請求到服務器,該服務器將獲取針對該用戶存儲的用戶信息並允許用戶登錄。 –

+0

不建議將它保存在會話中。它應該一定在cookie中,因爲當今天或者明天進入應用程序時,如果它被選中,應該把用戶和密碼放在文本框中記住我。如果我在第二天打開應用程序或關閉應用程序,會話將會消失。 – Necroimix