ASP.NET MVC HttpContext在LogOn之后获取IdentityName

AEM*_*iji 2 asp.net-mvc

HttpContext.Current.User.Identity.Name在LogOn之后返回null.我正在使用IIS7.0框架4.0.和vs 2010.我有另一个targetFramework是3.5的项目.它运作良好.但我的新项目的targetFramework是4.0.当调用HttpContext.Current.User.Identity.Name时,它返回null

Dar*_*rov 7

您应该发出能够使用这个属性之前登录后HTTP重定向.重定向后,您就可以使用它在后续请求.这是通常的模式:

public ActionResult LogOn()
{
    FormsAuthentication.SetAuthCookie("someuser", false);
    return RedirectToAction("foo");
}

[Authorize]
public ActionResult Foo()
{
    // use the logged in user here without problems
    string userName = User.Identity.Name;
    return View();
}
Run Code Online (Sandbox Code Playgroud)

  • 因为`User.Identity.Name`使用**Request**中存在的身份验证cookie来填充此属性,并且在调用`FormsAuthentication.SetAuthCookie`之后,请求中没有这样的cookie,它在响应中设置,以便客户端浏览器将在后续调用的请求中发送它.这就是为什么你应该在登录后始终重定向. (3认同)