ASP.NET MVC 登录不粘



我的 ASP.NET MVC 5 简单会员资格提供程序登录代码出现问题。代码如下:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel model, string returnUrl)
    {
        bool active = true;
        if (ModelState.IsValid && WebSecurity.Login(model.Email, model.Password, persistCookie: model.RememberMe))
        {
            UserDetail userModel = UserDetail.Initialize(model.Email);
            FormsAuthentication.SetAuthCookie(model.Email, true);
            active = userModel.ActiveBit;
            if (active)
            {
                return Redirect("~/");
            }
            else
            {
                WebSecurity.Logout();
                ModelState.AddModelError("", "Account is inactive.");
            }
        }
        else
        {
            ModelState.AddModelError("", "*Either the Username or Password provided is incorrect.");
        }
        return View(model);
    }

登录过程成功,我可以看到身份验证 cookie (.ASPXAUTH(在浏览器中。问题出现在下一页请求中。身份验证 cookie 被传递回服务器,但服务器似乎不再有登录记录。当我设置断点并在处理登录并请求新页面后(完成登录后重定向后(进行检查时,User.Identity.IsAuthenticated 是假的,WebSecurity.IsAuthenticated 和 WebSecurity.HasUserID 也是假的。WebSecurity.CurrentUserId 为 -1,WebSecurity.CurrentUserName 为空字符串。

这不是数据库连接问题,因为我确实成功进行身份验证。我往返服务器并返回,但我仍然没有经过身份验证,所以我看到的 CurrentUser == -1 的常见答案似乎不适用。

我是 MVC 的新手,但我有一个同事,他在查看我的代码方面有相当多的经验,他也找不到任何东西。感谢您的帮助。

默认情况下,

asp.net MVC5 web.config 不支持 FormsAuthentication ,请检查 Web 配置文件的以下部分,如果要使用 FormsAuthentication,请删除"<remove name="FormsAuthentication" />"

 <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>

身份验证超时配置

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
</system.web>

希望这有帮助。

最新更新