401即使在FormsAuthentication.SetAuthCookie()之后也未授权

Ph0*_*n1x 3 .net c# asp.net-mvc forms-authentication asp.net-mvc-5

我正在尝试使用基本表单身份验证实现ASP.NET MVC5应用程序.所以有我的登录方法:

    [HttpPost]
    [AllowAnonymous]
    public ActionResult Login(string email, string password, bool? rememberMe)
    {
        if (email.IsNullOrWhiteSpace() || password.IsNullOrWhiteSpace())
        {
            return RedirectToAction("Index");
        }

        UserEntity user = new UserEntity() {Email = email, PasswordHash = password};
        var userFromDb = _userService.FindUser(user);
        if (userFromDb != null)
        {
            FormsAuthentication.SetAuthCookie(userFromDb.Name, rememberMe.GetValueOrDefault());

            var a = HttpContext.User.Identity.IsAuthenticated; //This is still false for some reson
            return RedirectToAction("Index", "User");
        }

        return RedirectToAction("Index");
    }
Run Code Online (Sandbox Code Playgroud)

但是在重定向这个方法后,它给了我401 Unauthorized错误.似乎也像HttpContext.User.Identity.IsAuthenticated是假的.

你有什么想法/建议为什么会这样,以及如何解决它?


UPD:我也有来自auth的行webconfig概念,所以这不是原因

<authentication mode="Forms"> <forms loginUrl="~/Login/Index" /> </authentication>

Ph0*_*n1x 7

我找到了原因.出于某种原因,在我的webconfig中有一行,它可以抑制FormsAuthentication模块

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

因此,这条线FormsAuthentiction不起作用,但如果我们将其注释掉或删除,则所有工作都按预期工作.

  • 这是因为默认情况下MVC5不使用FormsAuthentication.它使用ASP.NET Identity,因此它会删除默认模板中的FormsAuthentication.当您替换它时,您没有重新启用FormsAuth. (2认同)