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

问题描述:

我正在尝试使用基本表单身份验证实现ASP.NET MVC5应用程序。 所以有我的登录方法:401即使在FormsAuthentication.SetAuthCookie()后仍未授权

[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"); 
    } 

但在重定向这种方法后马上给的我401 Unauthorized错误。 也似乎像HttpContext.User.Identity.IsAuthenticated是错误的。

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


UPD:我也有一条线webconfig概念从权威性,所以这不是一个理由

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

我找到了原因。出于某种原因,在我的webconfig有一条线,这抑制FormsAuthentication模块

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

所以这条线FormsAuthentiction不工作,但如果我们将其注释掉或删除,如预期的所有作品。

+2

这是因为默认情况下MVC5不使用FormsAuthentication。它使用ASP.NET标识,因此它将删除默认模板中的FormsAuthentication。当你替换它时,你没有重新启用FormsAuth。 – 2015-01-21 16:50:53

<authentication mode="Forms" />到你的web.config文件中<system.web>为它触发其影响。

+0

已经存在 – Ph0en1x 2015-01-21 08:46:48

+0

这就是我一直在寻找的东西,所以非常感谢! – JakobMillah 2017-04-24 12:04:02