ASP.NET Membership: Where is the current User ID stored?

Using ASP.NET membership, if I want to get information for the current user, I can call MembershipUser.GetUser()

So, somehow the system needs to know the identifier of the current user.

If this is correct, and all I want is the current user id, is there a way to get it without returning all the user information from the database?

I know that I can get the username of the current user using User.Identity.Name, but I need an identifier.

+5
source share
6 answers

, , API- ASP.NET Membership API . (User.Identity.Name). , Membership.GetUser() .

, Membership.GetUser() Membership.GetUser(User.Identity.Name). , , .

, , , - ( API- ASP.NET).

0

: , userID , ,

    MembershipUser user = Membership.GetUser();
    string UserID = user.ProviderUserKey.ToString();

, , () IPrincipal

+10

UserId, :

User.Identity.GetUserId();

UserName, :

User.Identity.Name;

:

var user = db.Users.Find(User.Identity.GetUserId());

, : User MVC5?

+2

, API , . . , , - :

public static object GetUserId() {
  return GetUserId(HttpContext.Current.User.Identity.Name, true);
}    
public static object GetUserId(string userName) {
  return GetUserId(userName, true);
}
public static object GetUserId(string userName, bool UpdateLastActivity) {
  using (SqlConnection c = new SqlConnection(CONNECTION_STRING)) {
    string sql = @"
DECLARE @UserId uniqueidentifier
SELECT @UserId=u.UserId
FROM dbo.aspnet_Applications AS a
  ,dbo.aspnet_Users AS u
  ,dbo.aspnet_Membership AS m
WHERE
  a.LoweredApplicationName=LOWER(@ApplicationName)
  AND u.ApplicationId=a.ApplicationId
  AND u.LoweredUserName=LOWER(@UserName)
  AND u.UserId=m.UserId;
IF @UserId IS NOT NULL AND @UpdateLastActivity=1
  UPDATE dbo.aspnet_Users
  SET LastActivityDate=@CurrentTimeUtc
  WHERE UserId=@UserId;
SELECT @UserId  
      ";
    using (SqlCommand cmd = new SqlCommand(sql, c)) {
      cmd.Parameters.AddWithValue("@ApplicationName", Roles.ApplicationName);
      cmd.Parameters.AddWithValue("@UserName", userName);
      cmd.Parameters.AddWithValue("@UpdateLastActivity", UpdateLastActivity);
      cmd.Parameters.AddWithValue("@CurrentTimeUtc", DateTime.UtcNow);
      object id = null;
      c.Open();
      id = cmd.ExecuteScalar();
      return id != DBNull.Value ? id : null;
    }
  }
}

, API- Membership GetUser()

+1

MembershipUser.UserName, Membership.GetUser(User.Identity.Name) , .

0

int userId = WebSecurity.CurrentUserId;

: fooobar.com/questions/939017/...

0

All Articles