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

2 Answers 2

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(); } 
Sign up to request clarification or add additional context in comments.

3 Comments

yes i understand you. i have test it/ and it worked. But why i can not call it after FormsAuthentication.SetAuthCookie("someuser", false);
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.
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
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.