我想在 mvc4 中创建登录和注销功能。在登录函数中,如果登录 cookie 存在且不为空,则用户处于登录模式,否则重定向到登录页面。在 logOut func 中,所有 cookie 和会话都清除并重定向到 login func,但在 login func 中存在登录 cookie!
登录:
public ActionResult Login()
{
if (Request.Cookies["login"] != null)
{
string login = Request.Cookies["login"].Value.ToString();
if (login != string.Empty)
{
//Get from service
Service srv = new Service();
UserItem userItem = srv.getUserItem(login);
srv.Close();
Session.Timeout = 30;
Session["login "] = login;
Session["userId"] = userItem.No;
Session["firstName"] = userItem.FirstName;
Session["lastName"] = userItem.LastName;
string loginName = userItem.LoginName;
FormsAuthentication.SetAuthCookie(loginName, false);
return Redirect(“Index”);
}
else
{
Return redirect("http://mySite/SignIn.aspx");
}
}
else
{
Return redirect("http://mySite/SignIn.aspx");
}
}
登出:
public ActionResult LogOut()
{
string login = Session["login"].ToString();
Request.Cookies["login"].Value = "";
Response.Cookies["login"].Value = "";
FormsAuthentication.SignOut();
HttpCookie c = Request.Cookies[FormsAuthentication.FormsCookieName];
c.Expires = DateTime.Now.AddDays(-1);
Session.Clear();
Request.Cookies.Clear();
Response.Cookies.Clear();
//FormsAuthentication.Initialize();
//string strRole = String.Empty;
//FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, "", DateTime.Now, DateTime.Now.AddMinutes(-30), false, strRole, FormsAuthentication.FormsCookiePath);
//Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)));
//Session.Abandon();
//// clear authentication cookie
//HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
//cookie1.Expires = DateTime.Now.AddYears(-1);
//Response.Cookies.Add(cookie1);
//// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
//HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
//cookie2.Expires = DateTime.Now.AddYears(-1);
//Response.Cookies.Add(cookie2);
//FormsAuthentication.RedirectToLoginPage();
return RedirectToAction("Login", "Usr");
}
网络配置:
<authentication mode="Forms">
<forms loginUrl="~/Usr/Login" timeout="30" />
</authentication>
我正在尝试评论代码,甚至评论这一行:
FormsAuthentication.SignOut();
即使我将 cookie 值设置为“”,但在登录页面中,此 cookie 具有旧值!并尝试了几种方法来清除cookie,比如设置过期一天后。但是……</p>
谢谢