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
2 Answers
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(); } 3 Comments
AEMLoviji
yes i understand you. i have test it/ and it worked. But why i can not call it after FormsAuthentication.SetAuthCookie("someuser", false);
Darin Dimitrov
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.Onkelborg
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