我剛開始嘗試使用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