Asp Net MVC 5用户身份IsAuthenticated返回false

时间:2019-04-10 07:17:24

标签: c# asp.net-mvc-5 forms-authentication

我正在使用表单身份验证并创建票证

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login([Bind(Include = "Username,Password,RememberMe")]LoginViewModel model)
{
   // other code here ....

    var ticket = new FormsAuthenticationTicket(
                        1,
                        user.Id.ToString(),
                        DateTime.Now,
                        DateTime.Now.AddDays(5),
                        model.RememberMe,
                        user.Roles.Select(c => c.Nome).FirstOrDefault(),
                        FormsAuthentication.FormsCookiePath
                        );

                    // Encrypt the ticket.
                    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                    // Create the cookie.
                    HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Name of auth cookie (it's the name specified in web.config) // Hashed ticket
                    authenticationCookie.Expires = DateTime.Now.AddDays(7);
                    // Add the cookie to the list for outbound response
                    Response.Cookies.Add(authenticationCookie);

                    return RedirectToAction("Index");

    // more code here...
}

这在Login控制器中用于验证用户。

现在,在此之后,我尝试手动重定向到登录控制器

 // GET: /Account/Login
        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index");
            }

            ViewBag.ReturnUrl = returnUrl ?? Url.Action("Index");

            return View();
        }

和User.Identity.IsAuthenticated返回false?为什么是这样?我可以看到在浏览器上创建的cookie

    <authentication mode="Forms">
  <forms name=".ADAuthCookie" loginUrl="~/Account/Login" defaultUrl="~/" timeout="2880" slidingExpiration="true" protection="All" />
</authentication>

编辑

只是说,如果我使用它,它将返回true。我不明白为什么它不能与票证一起使用

FormsAuthentication.SetAuthCookie(user.Id.ToString(), model.RememberMe);

0 个答案:

没有答案