HttpContext.User.Identity.Name在[authorization]里面是空的

本文关键字:authorization Identity User Name HttpContext | 更新日期: 2023-09-27 18:12:12

我重定向我的用户到这个ActionResult当他们点击登录和身份验证。它把它们带到这个方法:

[Authorize]
private ActionResult RouteRegistrationStep()
{
    Debug.Print(HttpContext.User.Identity.IsAuthenticated.ToString()); // false
    Debug.Print(HttpContext.User.Identity.Name); // blank
    return RedirectToAction("ContactInfo", "Adjuster");
}

为什么HttpContext.User.Identity.IsAuthenticated.ToString()是假的?而且,如果它是假的,为什么[Authorize]属性一开始就让它出现在方法中?

编辑:

这是重定向到RouteRegistrationStep()的登录方法:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid && db.Users.Where(x => x.username == model.username 
        && x.password == EncryptPassword(model.password)).Count() > 0)
    {
        FormsAuthentication.SetAuthCookie(model.username, model.RememberMe);
        return RedirectToLocal(returnUrl);
    }
    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model);
}
[Authorize]
private ActionResult RedirectToLocal(string returnUrl)
{
    if (Url.IsLocalUrl(returnUrl))
    {
        return Redirect(returnUrl);
    }
    else
    {
        return RouteRegistrationStep();
    }
}

HttpContext.User.Identity.Name在[authorization]里面是空的

操作过滤器只适用于公共操作方法,而不适用于私有操作方法。

此外,FormsAuthentication.SetAuthCookie方法将cookie写入HTTP响应,直到下一个请求才可用。您需要在用户获得授权之前进行重定向。从MSDN:

表单认证票证提供表单认证浏览器发出的下一个请求的信息。

设置验证cookie后,将用户重定向到另一个具有Authorize属性的操作,它应该可以正常工作。