0

我需要访问 cookie 以获取用户和密码,然后将它们设置在登录视图的文本框中,因为在该视图中选中了“记住我”。

注销方法

public ActionResult LogOff()
{
    //Session.Abandon();
    // sign out.
    FormsAuthentication.SignOut();
    return RedirectToAction("Index", "Login");
}

成功登录后初始化会话和 cookie。

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

登录视图的操作结果当我第一次注销然后尝试访问 cookie 时遇到问题,但它返回 null,因为我运行“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);
}
4

1 回答 1

0

如果他点击记住我复选框,您可以使用 javascript 来存储用户信息

利用

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

设定值

并在 Jquery 的文档就绪事件的登录页面上写下面的代码

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

希望这能解决您的问题。

于 2017-04-07T08:48:27.633 回答