views:

4348

answers:

3

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?

A: 

If you're looking for the name of the user from the membership provider, try something like this ...

var user = Membership.GetUser( HttpContext.Current.User.Identity.Name );

JP Alioto
If I need the user rather the user name, then I could simply use Membership.GetUser();:<|
Shimmy
+2  A: 

The value of HttpContext.Current.User.Identity.Name is set by the call to RedirectFromLoginPage. You can get the current user id from HttpContext.Current.User.Identity.Name once you are redirected to a new page. I'm not sure why you would need to access the user name through the User property in this context, couldn't you just use the value contained in tbUsername.Text?

Phaedrus
+6  A: 
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

blowdart
this is a good point. are you testing for the user name on the same page that sets the cookie/does the login? if so, check HttpContext.Current.User.Identity on a *subsequent* page.
Matt Sherman