Search code examples
c#asp.netado.netasp.net-membershipmembership

Retrieving UserId from Membership Provider


I am trying to retrieve the curent users UserId from the membership provider but something does not go the way I planned it to.Here is my code:

cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "forum_GetUsernameId";
cmd.Parameters.Add("@username" , user);
var data = cmd.ExecuteScalar();

 @username nvarchar 
   AS
 SELECT UserId
 FROM aspnet_Users
 WHERE UserName = @username

While debugging I noticed that data returns null witch can not be posible unless ExecuteScalar() is not the method I should be calling. Also user gets set to the curent username of that I am certain.

What am I doing wrong here?


Solution

  • If you're using SqlMemberShipProvider anyway it's simple:

    Guid userID = (Guid) Membership.GetUser().ProviderUserKey;