2

HttpContext.Current.User.Identity.Name returns null after LogOn. I am using IIS7.0 framework 4.0. and vs 2010. i have another project which targetFramework is 3.5. it works good. But targetFramework of my new project is 4.0. and when calling HttpContext.Current.User.Identity.Name it returns null

AEMLoviji
  • 3,217
  • 9
  • 37
  • 61

2 Answers2

7

You should issue an HTTP redirect after logging in before being able to use this property. After the redirect you will be able to use it on subsequent requests. Here's the usual pattern:

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();
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • yes i understand you. i have test it/ and it worked. But why i can not call it after FormsAuthentication.SetAuthCookie("someuser", false); – AEMLoviji Nov 27 '10 at 11:29
  • 3
    Because `User.Identity.Name` uses the authentication cookie present in the **Request** in order to populate this property and after calling `FormsAuthentication.SetAuthCookie` there's no such cookie in the request, it is set in the response so that the client browser will send it in the request on subsequent calls. That's why you should always redirect after logging in. – Darin Dimitrov Nov 27 '10 at 11:30
  • Well, you could set the principal manually if you, for some reason, don't want a redirect. However, I don't recommend that solution unless there are specific requirements – Onkelborg Nov 07 '12 at 08:38
0

Another solution is to use reflection to set the User.Identity.Name property on your logon page. Then the property is set without having to redirect to another page first, which is sort of a hack.