Request.IsAuthenticated总是错误的

你能告诉我为什么FormsAuthentication.SetAuthCookie(user.Name, false); 是不是导致Request.IsAuthenticated是真的?

这是我的代码:

 [HttpPost] public ActionResult LogIn(karcioszki.Models.UserLoginModel user) { if (ModelState.IsValid) { if (IsValid(user.Name, user.Password)) { FormsAuthentication.SetAuthCookie(user.Name, false); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "Login or password is incorrect"); } } return View(user); } 

如果声明:

 @if (Request.IsAuthenticated) { Home Cards @Html.ActionLink("Log out", "Logout", "User") @Html.Encode(User.Identity.Name) } 

另外,请告诉我,如何使它工作?

编辑:我在web.config(两者)中添加了身份validation,但它仍然无法正常工作。

                

我应该使用Windows还是其他模式?

我在MVC5项目中遇到了同样的问题。 解决方案是将以下行添加到system.webServer中的modules部分

   

你必须设置FormsAuthentication.SetAuthCookie(acct.UserName, true); validation用户后,请检查您是否必须在web.config中设置authentication mode="Forms"

在Web.config中添加以下代码

    

      

您正在检查用户是否已通过身份validation。 所以使用:

 if (User.Identity.IsAuthenticated) 

这将解决问题,并且如上所述将web.config中的身份validation元素设置为Forms而不是Windows。

我在MVC4 Web Application遇到了完全相同的问题。 此问题的另一个可能原因是IdentityModels.cs文件中的方法

 public async Task GenerateUserIdentityAsync(UserManager manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } 

确保DefaultAuthenticationTypesApplicationCookie

干杯,

我现在正在寻找约2个小时来解决问题。 如果你已经有一些设置就像你被告知在几个指南(如MSDN等),你仍然遇到问题,唯一能解决它的是添加:

       

在webconfig中。

就我而言,这是Chrome浏览器中的一个问题。 我刚刚删除了所有存储和运行的cookie。