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?
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.
You can achieve this by manually settings HttpContext. User: var identity = new ClaimsIdentity("Custom"); HttpContext. User = new ClaimsPrincipal(identity);
It is most likely stored in Managed Passwords: Click Start > Run. Enter "control userpasswords2"
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
Please try System.Web.HttpContext.Current.Request.LogonUserIdentity.Name
instead of User.Identity.Name
. It worked for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With