Results 1 to 6 of 6

Thread: How do i Get/Show the user ID in user.identity.name !?

  1. #1
    Member
    Join Date
    Feb 11
    Posts
    48

    How do i Get/Show the user ID in user.identity.name !?

    Hi

    I have this code that works, i get the user name.
    Code:
                If Request.IsAuthenticated Then
                    htmlString.Append("<h3>Generic User Information</h3>")
                    htmlString.Append("<b>name: </b>")
                    htmlString.Append(User.Identity.Name)
                    htmlString.Append("<br><b>Authenticated With: </b>")
                    htmlString.Append(User.Identity.AuthenticationType)
                    htmlString.Append("<br><br>")
                End If
    But if i add some code so i get this, then it will not work.
    Code:
                If Request.IsAuthenticated Then
                    htmlString.Append("<h3>Generic User Information</h3>")
                    htmlString.Append("<b>name: </b>")
                    htmlString.Append(User.Identity.Name)
                    htmlString.Append("<br><b>Authenticated With: </b>")
                    htmlString.Append(User.Identity.AuthenticationType)
                    htmlString.Append("<br><b>User ID: </b>")
                    htmlString.Append(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString())
                    htmlString.Append("<br><br>")
                End If
    How do i get the userid number, the primary key !?

    im using the user Authenticate Forms with a database.
    my code is.

    Global.asax
    Code:
        Public Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
            If Request.IsAuthenticated Then
                Dim conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString)
                conn.Open()
                
                Dim cmd As New OleDbCommand("Select Groups.Name FROM ((Roles INNER JOIN Groups ON Groups.GroupID = Roles.GroupID) INNER JOIN Users ON USERS.UserID = Roles.UserID) WHERE Users.Username=@UserName", conn)
                cmd.Parameters.AddWithValue("@UserName", User.Identity.Name)
                Dim reader As OleDbDataReader = cmd.ExecuteReader()
                Dim roleList As New ArrayList()
                While reader.Read()
                    roleList.Add(reader("Name"))
                    End While
                
                Dim roleListArray As String() = DirectCast(roleList.ToArray(GetType(String)), String())
                HttpContext.Current.User = New GenericPrincipal(User.Identity, roleListArray)
                
                reader.Close()
                conn.Close()
            End If
        End Sub
    And then i have this on my Loginpage
    Code:
        Private Function ValidateUser(ByVal userName As String, ByVal passWord As String) As Boolean
            Dim conn As OleDbConnection
            Dim cmd As OleDbCommand
            Dim lookupPassword As String
    
            lookupPassword = Nothing
    
            ' Check for an invalid userName.
            ' userName  must not be set to nothing and must be between one and 15 characters.
            If ((userName Is Nothing)) Then
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.")
                Return False
            End If
            If ((userName.Length = 0) Or (userName.Length > 15)) Then
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.")
                Return False
            End If
    
            ' Check for invalid passWord.
            ' passWord must not be set to nothing and must be between one and 25 characters.
            If (passWord Is Nothing) Then
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.")
                Return False
            End If
            If ((passWord.Length = 0) Or (passWord.Length > 25)) Then
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.")
                Return False
            End If
    
            Try
                ' Consult with your SQL Server administrator for an appropriate connection
                ' string to use to connect to your local SQL Server.
                conn = New OleDbConnection(ConfigurationManager.ConnectionStrings("ConnStr").ConnectionString)
                conn.Open()
    
                ' Create SqlCommand to select pwd field from the users table given a supplied userName.
                cmd = New OleDbCommand("SELECT Password, Username FROM Users WHERE Username=@userName AND Password=@passWord", conn)
                cmd.Parameters.Add("@userName", OleDbType.VarChar, 25)
                cmd.Parameters("@userName").Value = userName
                cmd.Parameters.Add("@passWord", OleDbType.VarChar, 25)
                cmd.Parameters("@passWord").Value = passWord
    
    
                ' Execute command and fetch pwd field into lookupPassword string.
                lookupPassword = cmd.ExecuteScalar()
    
                ' Cleanup command and connection objects.
                cmd.Dispose()
                conn.Dispose()
            Catch ex As Exception
                ' Add error handling here for debugging.
                ' This error message should not be sent back to the caller.
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " & ex.Message)
            End Try
    
            ' If no password found, return false.
            If (lookupPassword Is Nothing) Then
                ' You could write failed login attempts here to the event log for additional security.
                Return False
            End If
    
            ' Compare lookupPassword and input passWord by using a case-sensitive comparison.
            Return (String.Compare(lookupPassword, passWord, False) = 0)
    
        End Function
    
        Private Sub submit_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.ServerClick
            If ValidateUser(txtUserName.Value, txtUserPass.Value) Then
                Dim tkt As FormsAuthenticationTicket
                Dim cookiestr As String
                Dim ck As HttpCookie
    
                tkt = New FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now(), DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data")
                cookiestr = FormsAuthentication.Encrypt(tkt)
                ck = New HttpCookie(FormsAuthentication.FormsCookieName(), cookiestr)
                If (chkPersistCookie.Checked) Then ck.Expires = tkt.Expiration
                ck.Path = FormsAuthentication.FormsCookiePath()
                Response.Cookies.Add(ck)
    
                Dim strRedirect As String
                strRedirect = Request("ReturnURL")
                If strRedirect <> "" Then
                    Response.Redirect(strRedirect, True)
                Else
                    strRedirect = "default.aspx"
                    Response.Redirect(strRedirect, True)
                End If
            Else
                Session("logininfo") = "DBerror"
                Response.Redirect("login.aspx", True)
            End If
        End Sub
    And then i have the first code in this thread on my default.aspx page.

  2. #2
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 04
    Location
    The Granite City
    Posts
    21,731

    Re: How do i Get/Show the user ID in user.identity.name !?

    Hello siraero,

    When you say that it doesn't work, what does that mean?

    Do you get an exception? If so, what is the exception?

    Gary

  3. #3
    Member
    Join Date
    Feb 11
    Posts
    48

    Re: How do i Get/Show the user ID in user.identity.name !?

    hi gep13

    this is not working

    Code:
    htmlString.Append("<br><b>User ID: </b>")
    htmlString.Append(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString()
    i dont know if its right, but when search the net, about getting the id, i see GetUser/ProviderUserKey.
    When i user login, i need to use this users ID, i dont care if its in a session or something like that, i just need the users ID.
    The only thing i can get is the Users Name...

    How can i get the users ID when this user is logged in !?

  4. #4
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 04
    Location
    The Granite City
    Posts
    21,731

    Re: How do i Get/Show the user ID in user.identity.name !?

    Hello,

    Have you set a breakpoint on this line:

    Code:
    htmlString.Append(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString()
    What is the actual value of:

    Code:
    Membership.GetUser(User.Identity.Name).ProviderUserKey
    You still haven't set what isn't working?!?

    Does it throw an exception, or are you just getting an empty string?

    Gary

  5. #5
    Member
    Join Date
    Feb 11
    Posts
    48

    Re: How do i Get/Show the user ID in user.identity.name !?

    I get a System.NullReferenceException

    Detaljer om undtagelse: System.NullReferenceException: Objektreferencen er ikke indstillet til en forekomst af et objekt.

    Kildefejl:

    Linje 24: htmlString.Append(Membership.GetUser(User.Identity.Name).ProviderUserKey.ToString())

  6. #6
    ASP.NET Moderator gep13's Avatar
    Join Date
    Nov 04
    Location
    The Granite City
    Posts
    21,731

    Re: How do i Get/Show the user ID in user.identity.name !?

    Ok, now we are getting somewhere.

    When you set your breakpoint on the line that I mentioned, and you inspected the contents of each variable, which one was null?

    I suspect that this:

    Code:
    Membership.GetUser(User.Identity.Name)
    Is returning a null. Can you confirm?

    Gary

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •