我刚开始尝试使用MVC,并注意到授权属性限制对已验证用户的访问。不幸的是,它现在似乎不工作。如何使用MVC Authorize属性?
下面是我的代码:
Web.config文件:
<authentication mode="Forms">
<forms loginUrl="/Login/Index" timeout="30"/>
</authentication>
登录控制器:
[AllowAnonymous]
public ActionResult Index()
{
return View();
}
[HttpPost]
[AllowAnonymous]
public ActionResult ValidateLogin(UserLogin userLog)
{
if (userLog.UserName != "admin" || userLog.Password != "admin")
{
ModelState.AddModelError("Error Message", "Wrong Login Credentials.");
return View("Index", userLog);
}
return RedirectToAction("Index", "Home");
}
首页控制器:
[Authorize]
public ActionResult Index()
{
return View();
}
它仍然会阻止访问后进入一个 正确登录。
谢谢。
[HttpPost]
[AllowAnonymous]
public ActionResult ValidateLogin(UserLogin userLog)
{
if (userLog.UserName != "admin" || userLog.Password != "admin")
{
ModelState.AddModelError("Error Message", "Wrong Login Credentials.");
return View("Index", userLog);
}
// Signing in the user will make the Authorize attribute work!
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
return RedirectToAction("Index", "Home");
}
备选:
那么你验证用户,但你实际上并没有登录 – DavidG