HttpContext.User.Identity.IsAuthenticated永远不会是真的

Jac*_*ack 3 c# forms-authentication asp.net-mvc-4

登录

[HttpPost]
public ActionResult Login(LoginModel loginModel)
{
    if (ModelState.IsValid)
    {
        using (var _Db = new AccountContext())
        {
            var _UserAccount = _Db.UserAccounts.FirstOrDefault(u => u.Username == loginModel.Username && u.Password == loginModel.Password);

            if (_UserAccount == null)
            {
                ModelState.AddModelError("", "Account doesn't exist!");
            }
            else
            {
                FormsAuthentication.SetAuthCookie(loginModel.Username, false);
            }
        }
    }
    return RedirectToAction("Index", "Home");
}
Run Code Online (Sandbox Code Playgroud)

重定向或显示视图

public ActionResult Index()
{
    if (HttpContext.User.Identity.IsAuthenticated)
    {
        return View("Index");
    }
    else
    {
        return RedirectToAction("LoginPage");
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经完成了代码,可以看到使用正确的用户名调用SetAuthCookie. FormsAuthentication.SetAuthCookie(loginModel.Username, false);

什么可以阻止用户进行身份验证?

Dar*_*rov 7

什么可以阻止用户进行身份验证?

一个可能的原因是您忘记在web.config中启用表单身份验证:

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    ...
</system.web>
Run Code Online (Sandbox Code Playgroud)

您可能还想检查在调用SetAuthCookie方法后是否在浏览器中发出表单身份验证cookie.默认情况下,将调用此cookie .ASPXAUTH.如果存在此类cookie且票证尚未过期,则该HttpContext.User.Identity.IsAuthenticated方法将返回true.