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