【发布时间】:2017-09-02 12:59:27
【问题描述】:
我需要访问 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);
}
【问题讨论】:
-
根据本文:support.microsoft.com/en-us/help/910443/…、
FormsAuthentication.SignOut();无论如何都会删除 cookie。我假设在持久性 cookie 的情况下,您根本不会调用FormsAuthentication.SignOut();。 -
那么,在我的情况下,我不应该清理 cookie 吗?
-
我相信
FormsAuthentication.SignOut();只有在用户仍然有票证/cookie 但您的服务器上没有打开的会话时才应该使用。这将从用户的浏览器中删除票证并强制他再次“登录”。
标签: c# asp.net-mvc asp.net-mvc-5 formsauthentication formsauthenticationticket