为什么我得到 User.Identity.IsAuthenticated false

Why do I get User.Identity.IsAuthenticated false

我的 User.Identity.IsAuthenticated 是假的。我认为这是导致我的第二个问题的原因:我 无法使用 [Authorize] 装饰器访问 控制器。

我的代码是:

我找到了答案here:

When you call FormsAuthentication.SetAuthCookie upon successful authentication you are adding the authentication cookie to the response. This cookie will be stored on the client browser and will be sent on subsequent requests. So it is only on subsequent requests that the user will be considered as authenticated. So you need to always redirect after calling the SetAuthCookie method.

也就是说,你需要在调用FormsAuthentication.SetAuthCookie后立即添加RedirectToAction

[HttpPost]
[AllowAnonymous]
// The ASP.NET framework automatically puts a returnUrl query string parameter of the original
// page the user requested. You just need to add that parameter here to gain access to it
// (assuming you want to redirect the user back to the original requested page rather than 
// some start page).
public ActionResult Login(Login model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        if (System.Web.Security.Membership.ValidateUser(model.Nombre, model.Pass))
        {
            FormsAuthentication.SetAuthCookie(model.Nombre, model.Recordarme);

            // Redirect so the next request can see the user as authenticated
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }
        ViewBag.Error = "Usuario y/o contraseña incorrectos.";
    }
    return View(model);
}