首先,我是ASP.NET的新手,如果这个问题很愚蠢,那就很抱歉!
如果用户名/密码与数据库数据匹配,我已使用会话变量创建了登录系统! 问题是,虽然我能登录我不能注销
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
Session.RemoveAll();
return RedirectToAction("Index", "Home");
}
以上代码来自AccountController
@if (Session["LoggedUser"]!=null) {
<text>
Hello, @Html.ActionLink(Session["Username"].ToString(), "Manage", "Account", routeValues: null, htmlAttributes: new { @class = "username", title = "Manage" })!
@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) {
@Html.AntiForgeryToken()
<a href="javascript:document.getElementById('logoutForm').submit()">LogOff</a>
}
</text>} else {
<ul>
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>}
以上是来自_partialLogin
我的问题是,当我按下logOff时,该站点只是跳过控制器的LogOff部分并且会话未被清除,这意味着我仍然以用户身份登录 谢谢你的帮助
编辑: 这是登录页面的控制器,以备不时之需:
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
DefaultConnection dc = new DefaultConnection();
var Users = (from c in dc.NonActivated_Users select c).ToList<NonActivated_Users>();
foreach (NonActivated_Users nua in Users){
if (nua.Password_Hash == Hasher.HashString(model.Password) && nua.Username==model.UserName){
Session["LoggedUser"] = nua;
Session["Rights"] = 4; //non activated user
Session["Username"] = 0;
nua.LastActive = DateTime.Now;
dc.SaveChanges();
return RedirectToLocal(returnUrl);
}
}
var Users1 = (from c in dc.User select c).ToList<User>();
foreach (User au in Users1)
{
if (au.Password_Hash == Hasher.HashString(model.Password) && au.Username == model.UserName)
{
Session["LoggedUser"] = au;
if (au.Membership == false) {
Session["Rights"] = 3; //activated user non premium
}
else
{
Session["Rights"] = 2; //activated user premium
}
au.Last_Active = DateTime.Now;
dc.SaveChanges();
return RedirectToLocal(returnUrl);
}
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
答案 0 :(得分:1)
您没有设置FormsAuthentication
Cookie,因此您无法达到LogOff操作。
您需要使用[AllowAnonymous]
属性修饰LogOff操作,或在成功登录后设置身份验证Cookie
FormsAuthentication.SetAuthCookie(user.Username, false);
修改强>
我建议您使用User.Identity.IsAuthenticated
检查用户身份验证,而不是检查是否存在会话。
除此之外,您可以将会话变量存储到单个自定义对象,然后将该对象存储到单个会话中。在项目的后期阶段跟踪会话会更容易:)