1.登录时在controller中记录session,代码如下:
public ActionResult Login(UserLoginViewModel uViewModel) { if (ModelState.IsValid) { var user = db.ADUsers.SingleOrDefault(t => t.usrName == uViewModel.usrName && t.usrPassword == uViewModel.usrPassword); if (user != null) { FormsAuthentication.SetAuthCookie(uViewModel.usrName, false);//将用户名放入Cookie中 System.Web.HttpContext.Current.Session["usrName"] = uViewModel.usrName; //将用户名放入session中 return RedirectToAction("Index","Home"); } else { ModelState.AddModelError("usrName", "用户名不存在!"); } } return View(uViewModel); }
2.在View中,可以根据session进行判断是否正常登录
@if (Session["usrName"] != null) { using (Html.BeginForm("LogOff", "ADUsers", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) { @Html.AntiForgeryToken() <ul class="nav navbar-nav navbar-right"> <li> @Html.ActionLink("你好," + Session["usrName"] + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" }) </li> <li><a href="javascript:document.getElementById(‘logoutForm‘).submit()">注销</a></li> </ul> } } else { <ul class="nav navbar-nav navbar-right"> <li>@Html.ActionLink("登录", "Login", "ADUsers", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> <li>cookies:@Session["usrName"];</li> </ul>
3.注销时,记得将session清空
public ActionResult LogOff() { FormsAuthentication.SignOut(); System.Web.HttpContext.Current.Session["usrName"] = null; return RedirectToAction("Login"); }
时间: 2024-10-06 20:52:15