【发布时间】:2013-07-13 08:02:39
【问题描述】:
我想在 mvc4 中创建登录和注销功能。在登录函数中,如果登录 cookie 存在且不为空,则用户处于登录模式,否则重定向到登录页面。 在 logOut func 中,所有 cookie 和 session 都清除并重定向到 login func,但在 login func 中存在 login 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");
}
Web.config:
<authentication mode="Forms">
<forms loginUrl="~/Usr/Login" timeout="30" />
</authentication>
我正在尝试评论代码,甚至评论这一行:
FormsAuthentication.SignOut();
即使我将 cookie 值设置为“”,但在登录页面中,此 cookie 具有旧值! 并尝试了几种方法来清除cookie,比如设置过期一天后。但是……
谢谢
【问题讨论】:
-
忽略有更好的方法可以做到这一点,为了从浏览器中删除 cookie,您 1) 必须修改它以使其过期 和 2) 将其返回响应中的浏览器。您正在修改它,但浏览器不会知道,因为您没有返回它。
-
我知道我跑题了,但仍然建议你看看 ASP.Net Membership 提供者和 MVC 的 Authorize 属性。它消除了复杂的实现。
标签: c# asp.net-mvc cookies