我刚开始尝试使用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();
}
输入正确的登录信息后仍会阻止访问。
谢谢。
答案 0 :(得分:1)
尝试使用authenticationmanager的实际登录来扩展您的登录方法:
[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");
}
<强> ALTERNATIVE 强> ?: 我很关注FormsAuthentication,但到目前为止还没有使用它,也许这是你的选择,但AuthenticationManager很容易使用!
登录:
FormsAuthentication.SetAuthCookie(username, false);
退出:
FormsAuthentication.SignOut();