我试图在登录后立即在导航栏上添加一个注销按钮,但是由于某些原因Request.IsAuthenticated一直为假,所以我不明白为什么。除非您登录,否则我使用UserAuthenticationFilter阻止访问其他页面,但是我怀疑它是否相关。
从用户控制器中注销方法的一小段
{
public class UserController : Controller
{
[UserAuthenticationFilter]
[HttpGet]
public ActionResult Management()
{
using (CarsDBEntities db = new CarsDBEntities())
{
return View(db.Users.ToList());
}
}
[UserAuthenticationFilter]
public ActionResult Register()
{
return View();
}
[UserAuthenticationFilter]
[HttpPost]
public ActionResult Register(User user)
{
if (ModelState.IsValid)
{
using (CarsDBEntities db = new CarsDBEntities())
{
db.Users.Add(user);
db.SaveChanges();
}
ModelState.Clear();
ViewBag.Message = user.FirstName + " " + user.LastName + " successfully registered.";
}
return View();
}
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(User user)
{
using (CarsDBEntities db = new CarsDBEntities())
{
var usr = db.Users.SingleOrDefault(u => u.Email == user.Email && u.Password == user.Password);
if (usr != null)
{
Session["UserId"] = usr.UserId.ToString();
Session["Email"] = usr.Email.ToString();
Session["FirstName"] = usr.FirstName.ToString();
Session["LastName"] = usr.LastName.ToString();
return RedirectToAction("LoggedIn");
}
else
{
ModelState.AddModelError("", "Email or Password is incorrect!");
}
return View();
}
}
[UserAuthenticationFilter]
public ActionResult LoggedIn()
{
if (Session["UserId"] != null)
{
return RedirectToAction("Management");
}
else
{
return RedirectToAction("Login");
}
}
[ValidateAntiForgeryToken]
[HttpPost]
[Authorize]
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session.Abandon();
return RedirectToAction("Login", "User");
}
}
}
_LoginPartial.cshtml
@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("Logout", "User", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink(User.Identity.GetUserName(), "User", "Management")</li>
<li>@Html.ActionLink("Log out", "Logout", "User")</li>
<li><a href="javascript:document.getElementById('logoutForm').submit">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Log in", "Login", "User")</li>
</ul>
}
}
答案 0 :(得分:2)
您需要告知FormsAuthentication
用户已登录。
public ActionResult Login(User user)
{
using (CarsDBEntities db = new CarsDBEntities())
{
var usr = db.Users.FirstOrDefault(u => u.Email == user.Email && u.Password == user.Password);
if (usr != null)
{
FormsAuthentication.SetAuthCookie(usr.Email, false); // add this
Session["UserId"] = usr.UserId.ToString();
Session["Email"] = usr.Email.ToString();
Session["FirstName"] = usr.FirstName.ToString();
Session["LastName"] = usr.LastName.ToString();
return RedirectToAction("LoggedIn");
}
else
{
ModelState.AddModelError("", "Email or Password is incorrect!");
}
return View();
}
}
另外,请在FirstOrDefault
上使用SingleOrDefault