Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current.User.Identity.Name is always string.Empty

Hi I use a custom MembershipProvider.

I want to know the current username during an application scenario, but when I try accessing HttpContext.Current.User.Identity.Name it always returns string.Empty.

if (Membership.ValidateUser(tbUsername.Text, tbPassword.Text)) {     FormsAuthentication.SetAuthCookie(tbUsername.Text, true);     bool x = User.Identity.IsAuthenticated; //true     string y = User.Identity.Name; //""     FormsAuthentication.RedirectFromLoginPage(tbUsername.Text, cbRememberMe.Checked); } 

Am I missing something?

like image 313
Shimmy Weitzhandler Avatar asked Jun 29 '09 03:06

Shimmy Weitzhandler


People also ask

What is HttpContext current user identity Name?

It just holds the username of the user that is currently logged in. After login successful authentication, the username is automatically stored by login authentication system to "HttpContext.Current.User.Identity.Name" property.

How do you set HttpContext user identity for an application manually?

You can achieve this by manually settings HttpContext. User: var identity = new ClaimsIdentity("Custom"); HttpContext. User = new ClaimsPrincipal(identity);

Where is HttpContext user stored?

It is most likely stored in Managed Passwords: Click Start > Run. Enter "control userpasswords2"


2 Answers

FormsAuthentication.SetAuthCookie(tbUsername.Text, true); bool x = User.Identity.IsAuthenticated; //true string y = User.Identity.Name; //"" 

The problem you have is at this point you're only setting the authentication cookie, the IPrincipal that gets created inside the forms authentication module will not happen until there is a new request - so at that point the HttpContext.User is in a weird state. Once the redirect happens then, because it's a new request from the browser the cookie will get read before your page is reached and the correct user object created.

Cookies are only set on the browser after a request is completed.

As an aside RedirectFromLoginPage creates a forms auth cookie anyway, you don't need to do it manually

like image 68
blowdart Avatar answered Sep 28 '22 05:09

blowdart


Please try System.Web.HttpContext.Current.Request.LogonUserIdentity.Name instead of User.Identity.Name. It worked for me.

like image 29
sathya Avatar answered Sep 28 '22 04:09

sathya